Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference a property using Django's QuerySet.values_list?

Tags:

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?

like image 770
Huuuze Avatar asked Jan 26 '10 23:01

Huuuze


People also ask

What is the use of QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What does Values_list return in Django?

The values_list() method allows you to return only the columns that you specify.

Which can be used to retrieve an object directly instead of a QuerySet?

Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.


1 Answers

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() ] 
like image 160
zaca Avatar answered Oct 07 '22 13:10

zaca