pythondjangodjango-orm

Django ORM, append external field to QuerySet


I have a simple queryset resulting from this:

Books.objects.all()

Books is related to Authors like this:

Class Books:
    ...
    author = models.ForeignKey(Authors, on_delete=models.CASCADE)

Class Authors:
    id = models.AutoField(primary_key=True)
    name = models.CharField()

So for each book there's only one author.

I want to add to each instance of the Books queryset the related Author 's name, as in this query:

SELECT a.*, b.name 
FROM Books as a
JOIN Authors as b on a.author_id = b.id

I tried to read the documentation on Annonate or the selected_related method but didn't find a solution.


Solution

  • You annotate it with an F-expression:

    from django.db.models import F
    
    Books.objects.annotate(name=F('author__name'))