Django:查询多对一模型实例字段

时间:2013-06-01 20:04:09

标签: django model key

我一直在玩Django教程,并试图将模型实例的字段(通过外键)与另一个模型实例相关联。这就是我的意思:

模型文件:

from django.db import models

class Usercar(models.Model):
    make = models.CharField(max_length=200)
    model = models.CharField(max_length=200)
    year = models.DateTimeField('year of car')
    def __unicode__(self):
        return self.make

class Suggestcar(models.Model):
    usercar = models.ForeignKey(Usercar)
    make = models.CharField(max_length=200)
    model = models.CharField(max_length=200)
    year = models.DateTimeField('year of car')
    def __unicode__(self):
        return self.make

在shell中,当我尝试获取与用户车相关的建议车的内容时,这就是我得到的:

>>from django.utils import timezone
>>mycar1 = Usercar(make="Ford",model="Escort",year=timezone.now())
>>mycar1.save()
>>mycar1.suggestcar_set.create(make="Ford", model="Taurus", year=timezone.now())
>>mycar1.suggestcar_set.filter(id=1).make
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-    packages/django/core/management/commands/shell.pyc in <module>()
----> 1 mycar1.suggestcar_set.filter(id=1).make

AttributeError: 'QuerySet' object has no attribute 'make'

我怎样才能获得mycar1.suggestcar_set.filter(id = 1)?谢谢!

1 个答案:

答案 0 :(得分:2)

filter返回一个查询集,如果要访问其中的对象,则需要迭代查询集或从中获取第一个结果。

mycar1.suggestcar_set.filter(id=1)[0].make

如果您只想返回1个对象,则应该使用get

mycar1.suggestcar_set.get(id=1).make