Search code examples
pythondjangofiltermany-to-manymodels

Filtering in ManytoManyField


How to make a choice only from users who are in the group created in the admin panel? In Foreign Key, this could be done via limit_choices_to, and in MtM it is not known as. Google didn't help.

class Application(models.Model):

    STATUS_CHOICES = (
        ('In the work', 'В работе'),
        ('New', 'Новая'),
        ('Complited', 'Завершена')
    )

    author = models.ForeignKey(User, related_name = 'author', null = True)
    title = models.CharField(max_length=50)
    text = models.TextField()
    room = models.CharField(max_length = 5)
    published_date = models.DateField(blank=True, null=True, default = datetime.datetime.now)
    status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='New')
    owner = models.ManyToManyField(User)

    def __str__(self):
        return self.title

Solution

  • Maybe a din't understand what you really want, but you can use limit_choices_to in a M2M field.

    See the docs: https://docs.djangoproject.com/en/2.0/ref/models/fields/#manytomany-arguments