Reputation: 3017
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
Upvotes: 0
Views: 63
Reputation: 771
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:
Add tag to Question instance as,
quest_instance.tags.add(your_tag_instance)
To get all tags for question,
quest_instance.tags.all()
Get all questions for particular tag,
tag_inst.question_set.all()
Note: Relative queries may require minor updates.
Upvotes: 3