Adam Starrh
Adam Starrh

Reputation: 6968

Adding List of Related IDs to returned values in a Django Queryset

According to the example in Django's Docs, I can obtain a list of reverse related objects like this:

Blog.objects.values('entry__id')

Which would presumably give me the ids of all related Entry objects. If I wanted this information in addition to all the other information returned in a normal .values() call, is there a short way to add it on? Or do I need to explicitly list all of the models' fields in .values() to have the reverse keys included in the output?

Upvotes: 0

Views: 36

Answers (1)

Amine Messaoudi
Amine Messaoudi

Reputation: 2299

You can use annotate to add extra fields from foreign keys

from django.db.models import F

blogs = Blog.objects.all().annotate(entry_id=F('entry__id'))

for blog in blogs:
    print(blog.entry_id)

Upvotes: 1

Related Questions