I would like to use limit_choices_to
to reduce the set of choices for the Django admin of Model with a ManyToMany Field
when using an Inline.
Interestingly, the reason why I want to limit choices is for performance as I want to use a property of a parent model in the __str__
method of my related model class, and not limiting the choices causes prohibitively many SQL queries.
The following works
class ParentOfA(models.Model):
name = models.CharField(max_length=50, null=True)
class A(models.Model):
parent = models.ForeignKey(ParentOfA)
def __str__(self):
return "%s" % self.parent
class B(models.Model):
a = models.ManyToManyField(A, limit_choices_to={"a__name":'parent name'})
If I don't use an Inline in the admin form for B
(following the example in the docs).
E.g.
@admin.register(B)
class BAdmin(admin.ModelAdmin):
pass
However, with the inline the limit_choices_to
has no effect:
class BInline(admin.TabularInline):
model = B.A.through
@admin.register(B)
class BAdmin(admin.ModelAdmin):
inline = (BInline,)
Any suggestions?