Coder Perfect

get a list of ids in django models

Problem

How can I get a list of all the table’s id/primary keys? Assume I have the following table:

class Blog(models.Model)
  title = models.CharField()
  body = models.CharField()
  author = models.ForeignKey(Author)

Assume that author is an Author object in the field author. I’d like to gather all of the ids for blogs where the author is the same as the author.

I’m confident that I’ll be able to put it to good use.

    blogs = Blog.objects.filter(author=author)

He has a list of blog objects, but how can I acquire the list IDS/PK? “Select id from Blog where Author=author” is similar.

Asked by ibaguio

Solution #1

This may be accomplished with the values list method.

blogs = Blog.objects.filter(author=author).values_list('id', flat=True)

See the Django queryset documentation for further information.

Answered by Stepan Grigoryan

Solution #2

Blog.objects.filter(author=author).values_list('id', flat=True)

values list() returns a list of rows, each row containing a tuple containing all of the fields you specify as arguments, in the order you specified them. If you just supply a single field as an argument, flat=True will return a plain list rather than a list of tuples.

Answered by Andrew Gorcester

Solution #3

Blog.objects.filter(author=author).values_list('pk', flat=True)

For best practices, use pk instead of id.

Answered by Jorge Alberto

Solution #4

When iterated over, values list returns tuples. The value from the corresponding field or expression supplied into the values list is contained in each tuple ().

author = Blog.objects.filter(author=author)
ids    = author.values_list('pk', flat=True)

# list method get ids without parse the returning queryset

print(list(ids))

Answered by Sahir Saiyed

Post is based on https://stackoverflow.com/questions/22124549/django-models-get-list-of-id