Is it possible to reference a property using Djang

2019-02-06 14:07发布

问题:

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

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:

FieldError: Cannot resolve keyword 'full_name' into field

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?

回答1:

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

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


回答2:

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:

[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.