简体   繁体   English

Django:访问模型属性

[英]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. 为noobish问题道歉,我对Python和Django都是全新的,并试图制作我的第一个应用程序。

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 我知道如何在模型中使用unicode来指定更好的返回值,例如

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. 在您的情况下, about是一个QuerySet对象 ,而不是您的模型的实例。 Try 尝试

print about[0].title

Alternatively, use get() to retrieve a single instance of the model : 或者,使用get()来检索模型的单个实例

about = About.objects.get(id=1)
print about.title

Filter returns a QuerySet and not the single object you are looking for. Filter返回QuerySet,而不是您要查找的单个对象。 Use get instead of filter. 使用get而不是filter。

Methods that return new QuerySets 返回新QuerySet的方法

  • filter 过滤
  • ... ...

Methods that do not return QuerySets 不返回QuerySets的方法

  • get 得到
  • ... ...

http://docs.djangoproject.com/en/dev/ref/models/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. 正如文档所解释的那样, filter 总是返回一个QuerySet,它是一个类似列表的项集合,即使只有一个元素与过滤条件匹配。 So you can slice the list to access your element - about[0] - or, better, use get() instead: 所以你可以切片列表来访问你的元素 - about[0] - 或者更好的是,使用get()代替:

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) 现在about是一个对象(一行)

filter returns list, so for accessing items in list you must use index (about[0]) or for loop .but get return exactly one row. filter返回列表,以便用于访问列表中的项目必须使用index (约[0])或for loop 。但get返回一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM