Python Django 查询列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3673985/
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-08-18 12:10:45  来源:igfitidea点击:

Django query to list

pythondjango

提问by JPC

I have a database which has records with several fields containing some info.

我有一个数据库,其中包含包含一些信息的多个字段的记录。

To get all the data in the table matching some filter I'd do this:

要获取与某些过滤器匹配的表中的所有数据,我会这样做:

records = Record.objects.filter(fieldA='a')

records, I suppose, is a QuerySet object and contains a "list" of records. Is that correct?

我想记录是一个 QuerySet 对象,包含一个记录“列表”。那是对的吗?

Now let's say I want a list of the values in one field.

现在假设我想要一个字段中的值列表。

If I do this:

如果我这样做:

records = Record.objects.filter(fieldA='a').only('fieldB')

I still get a queryset, but now it has some deferred fields. What I want is just a list of the values I meant to grab aka fieldB. I also want to be able to grab the distinct values of fieldB. I suppose I could just iterate over each record, pull out fieldB, add it to a list if it's not already there, and there it is, but there's gotta be a better way.

我仍然得到一个查询集,但现在它有一些延迟字段。我想要的只是我打算抓取的值的列表,又名 fieldB。我还希望能够获取 fieldB 的不同值。我想我可以遍历每条记录,拉出 fieldB,如果它不存在,则将其添加到列表中,并且确实存在,但是必须有更好的方法。

Thanks!

谢谢!

EDIT: I think what I'm looking for is

编辑:我想我要找的是

Record.objects.values_list('fieldB')

采纳答案by JPC

回答by Joshua Cook

I am posting the comment by Jameshere to make it more prominent. It was certainly what I was looking for.

我在这里张贴詹姆斯的评论,以使其更加突出。这当然是我正在寻找的。

I wanted a list of values. Using the QuerySetmethod .list_values()returned a list of tuples. To get a list of values, I needed the option flat=True.

我想要一个值列表。使用该QuerySet方法.list_values()返回一个元组列表。要获取值列表,我需要选项flat=True.

Record.objects.values_list('fieldB', flat=True)