SQL django 模型:获取 id 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22124549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:12:51  来源:igfitidea点击:

django models: get list of id

sqldjangodjango-models

提问by ibaguio

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 authoris an Author object. I want to get all the ids of Blog where author=author

假设字段author是一个 Author 对象。我想获取作者=作者的博客的所有ID

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"

并以列表形式获取所有博客对象,但如何获取列表 IDS/PK?类似于“从博客中选择 id,其中作者=作者”

回答by Stepan Grigoryan

You can do this using values_listmethod.

您可以使用values_list方法来做到这一点。

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

See more at the Django queryset documentation.

Django 查询集文档中查看更多信息

回答by Andrew Gorcester

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=Trueto get a plain list instead of a list of tuples.

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

回答by Jorge Alberto

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

Put pkinstead id, just for best practices.

pk代替id,只是最佳实践。