0

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

4

1 回答 1

2

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

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

如果你只想返回 1 个对象,你真的应该使用get

mycar1.suggestcar_set.get(id=1).make
于 2013-06-01T20:10:36.980 回答