Django models filter objects for ManyToManyField

Question:

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,
)
Asked By: MrDan4es

||

Answers:

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.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.