Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: accessing model attributes

Apologies for the noobish question, I am completely new to both Python and Django and trying to make my first app.

I have a simple class

class About(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    date = models.DateTimeField('date added')

to which I've added a single record. I can access this with

about = About.objects.filter(id=1)

however, if I try to use dot syntax to access its attributes I get the following error

    >>> about.title
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'title'

I know how to use unicode in the model to specify a nicer return value such as

def __unicode__(self):
    return self.title

should I be using this to format the model data into a dictionary/list? Or am I just completely missing some default behaviour?

like image 385
igniteflow Avatar asked Apr 24 '11 09:04

igniteflow


3 Answers

In your case, about is a QuerySet object, not an instance of your model. Try

print about[0].title

Alternatively, use get() to retrieve a single instance of the model:

about = About.objects.get(id=1)
print about.title
like image 55
Blair Avatar answered Oct 23 '22 10:10

Blair


Filter returns a QuerySet and not the single object you are looking for. Use get instead of filter.

Methods that return new QuerySets

  • filter
  • ...

Methods that do not return QuerySets

  • get
  • ...

http://docs.djangoproject.com/en/dev/ref/models/querysets/

like image 44
Pickels Avatar answered Oct 23 '22 10:10

Pickels


As the documentation explains, filter always returns a QuerySet, which is a list-like collection of items, even if only one element matches the filter condition. So you can slice the list to access your element - about[0] - or, better, use get() instead:

about = About.objects.get(id=1)
print about.title
like image 38
Daniel Roseman Avatar answered Oct 23 '22 10:10

Daniel Roseman