Let's say this is my models.py
file:
class Paper(models.Model):
title = models.CharField(max_length=20, null=False, blank=False)
class Author(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
papers = models.ManyToManyField(Paper, null=False, blank=False)
An author can have multiple papers and a paper can have multiple authors. I need to get all the papers titles for a given author.
In my views.py
, once I have an author object, I need to get a list with all the titles of his papers. I'm doing this:
user = User.objects.get(username=request.user)
author = Author.objects.get(user=user)
papers = [paper.title for paper in author.papers.all()]
Is there a way in Django to make this query without having to iterate over the author papers? Maybe there is a built-in function or something that I'm missing, any suggestions?
CodePudding user response:
This should be enough
papers_by_author = Author.objects.filter(
user__username=request.user
).values('papers__title')
apart from this if you prefetch_related in your code. you ll have some speed.
Author.objects.get(user=user).prefetch_related('papers')
CodePudding user response:
Also you can get all papers of certain author for example, to get an author like in your code:
author = Author.objects.get(user=user)
and then to get all the papers of this autor:
author.papers.values_list("title", flat=True)
the result is a list with title values only.
To sum up, values_list() with flat=True is what You need here!