问题
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?
回答1:
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')
回答2:
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
回答3:
We can select required fields over values.
Employee.objects.all().values('eng_name','rank')
回答4:
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 %}
来源:https://stackoverflow.com/questions/7503241/django-models-selecting-single-field