是否可以使用Django的QuerySet.values_list引用属性?

时间:2021-10-20 01:35:04

I have a custom property on my Django model that returns the full name of a Person:

我在Django模型上有一个自定义属性,它返回一个人的全名:

class Person(models.Model):
  first_name = models.CharField(max_length=30)
  last_name = models.CharField(max_length=30)

def _get_full_name(self):
  return "%s %s" % (self.first_name, self.last_name)
full_name = property(_get_full_name)

When I create a query, I'd like to reference that property. For example:

在创建查询时,我希望引用该属性。例如:

people = Person.objects.all().values_list('full_name')

Unfortunately, Django yields the following FieldError:

不幸的是,Django产生了以下的FieldError:

FieldError: Cannot resolve keyword 'full_name' into field

FieldError:无法将关键字“full_name”解析到字段

Long story short, is it possible to access a custom property via the values_list() method? If not, does anyone have any suggestions on how to best remedy this problem?

长话短说,是否可以通过values_list()方法访问自定义属性?如果没有,有人对如何最好地解决这个问题有什么建议吗?

2 个解决方案

#1


15  

full name is not a field in the django model, it is not possible. you can use list comprehensions

全名不是django模型中的字段,它是不可能的。您可以使用列表理解

[person.fullname for person in Person.objects.all() ] 

#2


15  

values_list can only work on fields retrieved directly from the database. As zaca notes, you'll need a list comprehension on the actual queryset:

values_list只能在直接从数据库检索的字段上工作。正如zaca所指出的,您需要在实际的queryset上有一个列表理解:

[person.fullname for person in Person.objects.all()]

Don't over-use values_list. It's just meant as a means of limiting the db query, for when you know you'll only ever need those particular fields. For almost all uses, getting the standard queryset is efficient enough.

不要过分使用values_list。它只是作为一种限制db查询的方法,因为当您知道您只需要那些特定的字段时。对于几乎所有的用途,获得标准的queryset就足够有效了。

#1


15  

full name is not a field in the django model, it is not possible. you can use list comprehensions

全名不是django模型中的字段,它是不可能的。您可以使用列表理解

[person.fullname for person in Person.objects.all() ] 

#2


15  

values_list can only work on fields retrieved directly from the database. As zaca notes, you'll need a list comprehension on the actual queryset:

values_list只能在直接从数据库检索的字段上工作。正如zaca所指出的,您需要在实际的queryset上有一个列表理解:

[person.fullname for person in Person.objects.all()]

Don't over-use values_list. It's just meant as a means of limiting the db query, for when you know you'll only ever need those particular fields. For almost all uses, getting the standard queryset is efficient enough.

不要过分使用values_list。它只是作为一种限制db查询的方法,因为当您知道您只需要那些特定的字段时。对于几乎所有的用途,获得标准的queryset就足够有效了。