Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Django admin. Limit choices of many to many field

I have a Many to Many field. I'd like to limit the choices the admin shows in its M2M widget.

I have a model like this:

class A(models.Model):
    b_field = models.ManyToManyField(B)

class B(models.Model):
    available = models.BooleanField()

How do I limit the B objects shown in the widget only to those who have available = True?

Upvotes: 10

Views: 6874

Answers (1)

Sagar Ramachandrappa
Sagar Ramachandrappa

Reputation: 1461

The limit_choices_to option might help you,

Sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.

For eg,

class A(models.Model):
    b_field = models.ManyToManyField(B, limit_choices_to={'available': True})

Upvotes: 16

Related Questions