django模型:获取id列表。

时间:2022-06-08 18:20:39

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

如何获取表的所有id/主键的列表。假设我有这张桌子:

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

假设字段作者是一个author对象。我想获得所有的id,其中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"

将所有的博客对象以列表形式显示出来,但是如何获得列表id /PK呢?类似于“从Author= Author中选择id”

2 个解决方案

#1


43  

You can do this using values_list method.

您可以使用values_list方法进行此操作。

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

See more at the django queryset documentation.

请参阅django queryset文档。

#2


43  

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.

values_list()给出行的列表,每一行都是您指定为参数的所有字段的元组,按顺序排列。如果只将一个字段作为参数传入,还可以指定flat=True以获得一个普通的列表,而不是元组列表。

#1


43  

You can do this using values_list method.

您可以使用values_list方法进行此操作。

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

See more at the django queryset documentation.

请参阅django queryset文档。

#2


43  

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.

values_list()给出行的列表,每一行都是您指定为参数的所有字段的元组,按顺序排列。如果只将一个字段作为参数传入,还可以指定flat=True以获得一个普通的列表,而不是元组列表。