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?
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
Filter returns a QuerySet and not the single object you are looking for. Use get instead of filter.
Methods that return new QuerySets
Methods that do not return QuerySets
http://docs.djangoproject.com/en/dev/ref/models/querysets/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With