我一直在玩 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 中,当我尝试获取与 usercar 相关的Suggestcar 时,我得到了以下结果:
>>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) 的品牌?谢谢!