foreignkey方法未添加到用户对象

时间:2013-10-15 12:33:45

标签: django django-models

我在我的第一个django网站上使用以下模型。但我目前在如何访问用户的意愿方面遇到了问题。

class Group(models.Model):
    title = models.CharField(max_length=100)
    users = models.ManyToManyField(User, related_name='group_users')
    description = models.TextField()
    added = models.DateTimeField()
    owner = models.ForeignKey(User)
    def __unicode__(self):
        return self.title

class Wish(models.Model):
    name = models.CharField(max_length=50)
    user = models.ForeignKey(User, related_name='wish_user')
    bought = models.IntegerField(default=0)
    bought_by = models.ForeignKey(User, related_name='wish_buyer')
    added_by = models.ForeignKey(User, related_name='wish_adder')
    cost = models.FloatField()
    added = models.DateTimeField()
    def __unicode__(self):
        return self.name
    def is_bought(self):
        return self.bought % 2 == 1
    def is_editable(self):
        return self.added >= timezone.now() - datetime.timedelta(hours=1)

当我去django shell时,我得到以下内容:

$ ./manage.py shell
>>> from django.contrib.auth.models import User
>>> from wish.models import Wish, Group
>>> user1 = User.objects.filter(id=1)[0]
>>> user1.group_set.all()
[]
>>> user1.wish_set.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'wish_set'
>>>

为什么User对象不会像获取group_set一样获得wish_set?

1 个答案:

答案 0 :(得分:3)

那是因为您将其重命名为wish_userwish_buyerwish_adder。对于该群组,wish_set属性ownergroup_users明确related_name

<field name>_set参数告诉Django如何命名反向关系。如果没有给出它将是{{1}}