开发者

Django: accessing model attributes

开发者 https://www.devze.com 2023-02-28 14:47 出处:网络
Apologies for the noobish question, I am completely new to both Python and Django and trying to make my first app.

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 m开发者_开发知识库odel 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

  • filter
  • ...

Methods that do not return QuerySets

  • get
  • ...

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 want get just one row

about = About.objects.get(pk=1)

now about is an object(one row)

filter returns list, so for accessing items in list you must use index(about[0]) or for loop.but get return exactly one row.

0

精彩评论

暂无评论...
验证码 换一张
取 消