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
?
To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With