简体   繁体   中英

django models: retrieve foreign key related data as a list inside a response

I have to models: Question and Tags, with "many to many" relations between them.

 class Tag(models.Model):
    title = models.CharField(max_length=120)

    def __str__(self):
        return self.title


 class Question(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    tags = models.ManyToManyField(Tag, blank=True)

    title = models.CharField(max_length=120)
    text = models.TextField() 
    is_active = models.BooleanField(default=True)
    creation_date = models.DateTimeField(default=datetime.now)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-creation_date']

When i trying to get questions with associated tags i am getting copies of questions with one tag in it.

thats how i try to retrieve questions :

list(Question.objects.all().filter(is_active__exact=True).values('id', 'title', 'tags'))

i am getting result like this :

{'id': 3, 'tags': 1, 'title': 'question 3'}{'id': 3, 'tags': 2, 'title': 'question 3'}{'id': 2, 'tags': 2, 'title': 'question 2'}{'id': 2, 'tags': 3, 'title': 'question 2'}{'id': 1, 'tags': 1, 'title': 'question 1'}{'id': 1, 'tags': 2, 'title': 'question 1'}{'id': 1, 'tags': 3, 'title': 'question 1'}

Is there a way to get questions so that all tags associated with it are in the form of a single list. something like this:

{'id': 3, 'tags': [1, 2], 'title': 'question 3'}{'id': 2, 'tags': [2, 3], 'title': 'question 2'}{'id': 1, 'tags': [1, 2, 3], 'title': 'question 1'}

Nice question, I think you can try with something like this:

questions = Question.objects.filter(is_active__exact=True).prefetch_related('tags')
[{'id': question.id, 'title': question.title, 'tags': [tag.id for tag in question.tags.all()]} for question in questions]

More information about prefetch_related and List Comprehension .

Happy coding ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM