我一直在玩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)?谢谢!