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 is a 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"
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.
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.
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 is a 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"
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.
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.
0 commentaires:
Enregistrer un commentaire