Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 713
Alejandro Veintimilla Avatar asked Dec 16 '16 21:12

Alejandro Veintimilla


People also ask

How do you define many-to-many fields in Django?

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.


1 Answers

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})
like image 105
Sagar Ramachandrappa Avatar answered Sep 26 '22 08:09

Sagar Ramachandrappa