131

How do i get a list of all id/primary key for a table. Say i have this table:

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

assume the field author is an Author object. I want to get all the ids of Blog where author=author

i know i can use

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

and get all the blog objects in a list form, but how do i get the list IDS/PK? Similar to "Select id from Blog where Author=author"

3
  • 1
    I am curious why you want this? Usually you don't deal with the primary key as its managed by django. Commented Mar 2, 2014 at 6:24
  • @burhan its kinda complicated, i need to use the list of PK/ID for another query, w/c is something like not_authored_blog = Author.objects.exclude(blog__id__in=blogs). i have another table which has FK to 'blog' and want to get the objects in the other table that is not FK in 'blog'. more complicated than that though
    – ibaguio
    Commented Mar 2, 2014 at 11:36
  • You can get around this by checking if the blog_set related manager has any records; if its empty, then this Author has no blogs. It will be a lot better than doing your exclude query, which might be translated as a large NOT IN clause. Commented Mar 2, 2014 at 11:38

4 Answers 4

253

You can do this using values_list method.

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

See more at the Django queryset documentation.

2
  • 3
    Is there any way to get those ids without parse the returning queryset? I get <QuerySet [13, 14, 15]> and I want that list of ids. Is any pythonic way to avoid iterate over the rows?
    – RuBiCK
    Commented May 15, 2020 at 17:50
  • 3
    list method get ids without parse the returning queryset. print(list(ids)) Commented Aug 7, 2020 at 10:56
78
Blog.objects.filter(author=author).values_list('id', flat=True)

values_list() gives a list of rows, each row a tuple of all of the fields you specify as arguments, in order. If you only pass a single field in as an argument, you can also specify flat=True to get a plain list instead of a list of tuples.

1
  • 27
    It is best to use pk instead of id, the internal value pk will always point to the primary key field, even if its not called "id". Commented Mar 2, 2014 at 6:25
12
Blog.objects.filter(author=author).values_list('pk', flat=True)

Put pk instead id, just for best practices.

7

values_list it returns tuples when iterated over. Each tuple contains the value from the respective field or expression passed into the values_list().

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))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.