jtd92
jtd92

Reputation: 379

Retrieving a specific field from Django query

I am trying to get the type field from filtering by name. So I am trying to do something like:Example.objects.get(type).filter(name_exact="Sheep") and it should return Animal But its not successful.

models.py

class Example(models.Model):

    type = models.CharField(max_length=50, choices=CATEGORY_TYPE) #i.e Class, Type, Commodity, Market, Breed
    name = models.CharField(max_length=50) 

    def __str__(self):
        return u"%s" % (self.name)

Upvotes: 0

Views: 6407

Answers (1)

argaen
argaen

Reputation: 4245

If you want to get the type field of an instance:

t = Example.objects.get(name="Sheep").type

The get(name="Sheep") returns an example instance so you can do:

obj = Example.objects.get(name="Sheep")
print obj.type
print obj.name
obj.name = "Whatever" # assign new value to name
obj.save()            # save the changes to the db

On the other hand, if you need to do that with a queryset rather than with an object instance, you can use the values or values_list functions (examples extracted from the docs):

>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]
>>> Entry.objects.values_list('id', 'headline')
[(1, u'First entry'), ...]

Upvotes: 4

Related Questions