Home > OS >  Django models filter objects for ManyToManyField
Django models filter objects for ManyToManyField

Time:07-29

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

CodePudding user response:

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.

  • Related