Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django models filter objects for ManyToManyField

For example I have a model:

class User(models.Model):
    is_active = models.BooleanField(
        'Is active user?',
        default=True
    )
    friends = models.ManyToManyField(
        'self',
        default=None,
        blank=True,
    )

How can I filter only active users in ManyToManyField?
(It won’t work, just my ideas, ManyToManyField need Model in to=)

queryset = User.objects.filter(is_active=True)
friends = models.ManyToManyField(
    queryset,
    default=None,
    blank=True,
)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can work with limit_choices_to=… [Django-doc] to limit the choices of adding an element to a ManyToManyField, so here you can implement this as:

class User(models.Model):
    is_active = models.BooleanField(
        'Is active user?',
        default=True
    )
    friends = models.ManyToManyField(
        'self',
        limit_choices_to={'is_active': True}
    )

This will filter the set of available Users in a ModelForm that you construct for that model, and in the ModelAdmin for that model.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading