django模型选择单个字段

问题:django模型选择单个字段

我有一个称为的表/模型Employees,我想将单个字段的所有行作为查询集。

我知道我可以这样做(希望我做得对):

emp_list = Employees.objects.get(all)
emp_names = emp_list.eng_name

是否要在数据库中查询所有字段并且仅使用一个字段?是否有更好(更快)的方法?

I have a table/models called Employees and I would like to get all rows of a single field as a queryset.

I know I can do it like this (hope I’m doing this right even):

emp_list = Employees.objects.get(all)
emp_names = emp_list.eng_name

Would query the database for all fields and using only one? Is there a better (faster) way of doing this?


回答 0

Employees.objects.values_list('eng_name', flat=True)

这将创建所有eng_names的平面列表。如果您希望每行多于一个字段,则不能做一个平面列表:这将创建一个元组列表:

Employees.objects.values_list('eng_name', 'rank')
Employees.objects.values_list('eng_name', flat=True)

That creates a flat list of all eng_names. If you want more than one field per row, you can’t do a flat list: this will create a list of tuples:

Employees.objects.values_list('eng_name', 'rank')

回答 1

除了values_list丹尼尔 提到你也可以使用only(或defer为相反的效果),只得到有他们的ID和指定的字段对象的查询集:

Employees.objects.only('eng_name')

这将运行一个查询:

SELECT id, eng_name FROM employees

In addition to values_list as Daniel mentions you can also use only (or defer for the opposite effect) to get a queryset of objects only having their id and specified fields:

Employees.objects.only('eng_name')

This will run a single query:

SELECT id, eng_name FROM employees

回答 2

我们可以在值上选择必填字段。

Employee.objects.all().values('eng_name','rank')

We can select required fields over values.

Employee.objects.all().values('eng_name','rank')

回答 3

Oskar Persson的答案是处理该数据的最佳方法,因为当我们获得对象实例(很容易迭代以获取道具)而不是简单的值列表时,可以更轻松地将数据传递到上下文并从模板正常对待数据。

之后,您可以轻松获得所需的道具:

for employee in employees:
    print(employee.eng_name)

或在模板中:

{% for employee in employees %}

    <p>{{ employee.eng_name }}</p>

{% endfor %}

Oskar Persson’s answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list.

After that you can just easily get the wanted prop:

for employee in employees:
    print(employee.eng_name)

Or in the template:

{% for employee in employees %}

    <p>{{ employee.eng_name }}</p>

{% endfor %}

回答 4

您可以像这样在过滤器旁边使用values_list;

active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True)

在这里更多细节

You can use values_list alongside filter like so;

active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True)

More details here