user3384985 user3384985 - 6 days ago 5
Python Question

How to join multiple records of a model to another model in Django?

I need to set some tags to a question. In

Question
model i use
Tag
as
ForeignKey
-

class Tag(models.Model):
tag_text = models.CharField(max_length = 200)

class Question(models.Model):
tag = models.ForeignKey(Tag, on_delete = models.CASCADE)


What i see in back end for a
Question
can select one
Tag
but i want a single
Question
can select multiple
Tags
.

I am confused what it would be -
ManyToMany
/
OneToMany
/...

Thanks

Answer

Use ManyToMany relationship.

As one Question can have multiple tags, as well as one Tag can be there in multiple questions.

class Tag(models.Model):
    tag_text = models.CharField(max_length = 200)

class Question(models.Model):
    tag = models.ManyToManyField(Tag)

Relative queries:

  1. Add tag to Question instance as,

    quest_instance.tags.add(your_tag_instance)
    
  2. To get all tags for question,

    quest_instance.tags.all()
    
  3. Get all questions for particular tag,

    tag_inst.question_set.all()
    

Note: Relative queries may require minor updates.

Comments