MrDan4es
MrDan4es

Reputation: 43

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,
)

Upvotes: 2

Views: 72

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

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.

Upvotes: 2

Related Questions