Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add filtered ManyToMany Field Relation

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Or how I can achieve that.

>Solution :

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} )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading