Home > Mobile >  How to add filtered ManyToMany Field Relation
How to add filtered ManyToMany Field Relation

Time:08-31

Let's say;

#models.py

choices = (
    (1, Published),
    (0, Draft)
)

Class Question(models.Model):
    question =  models.CharField(max_length=200)
    status = models.IntegerField(
        choices=choices, default=0)

class Survey(models.Model):
    question = ManytoManyField(Question)

So I want the Questions to be available for the many-to-many field if the status of the question is 1 or say Published

For that can we do that?

ManytoManyField(Question.objects.filter(status=1))

Or how I can achieve that.

CodePudding user response:

all that you need is limit_choices_to attribute: more here: https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ManyToManyField.limit_choices_to

in your case:

class Survey(models.Model):
    question = ManytoManyField(Question, limit_choices_to={'status':1} )
  • Related