2011-04-11 30 views
1

这似乎是一个非常微不足道的问题,但它正在杀死我。Django ManyToManyField错误对象没有属性'location_set'

models.py

class Location(models.Model): 
    place = models.CharField("Location", max_length=30) 
    [...] 

class Person(models.Model): 
    first = models.CharField("First Name", max_length=50) 
    [...] 
    location = models.ManyToManyField('Location') 

从贝:

>>> from mysite.myapp.models import * 
>>> p = Person.objects.get(id=1) 
>>> p 
<Person: bob > 
>>> l = Location(place='123 Main') 
>>> p.location_set.add(l) 
>>> p.save() 
Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
AttributeError: 'Person' object has no attribute 'location_set' 

我真的没有看到什么我失踪。

回答

2

您不应该使用p.location.add()location_set<modelname>_set是该模型的reverse lookup的默认名称。

1

location_set将是一个落后的关系的默认名称,但是既然你已经定义的Person模型ManyToManyField,您可以通过字段名称访问相关经理:

p.location.add(l) 

考虑到这一点,将ManyToManyField命名为复数名词更有意义,例如

class Person(models.Model): 
    first = models.CharField("First Name", max_length=50) 
    [...] 
    locations = models.ManyToManyField('Location') 

而且,从内存中,当您尝试模型实例添加到许多一对多的关系,该实例之前必须将保存。

+0

感谢您的支持。我没有意识到“前进”和“后退”之间存在区别。这是有原因的吗?显然,映射表本身不会产生任何这样的“方向性”。 – jal 2011-04-13 01:27:13

+0

这是正确的,但该领域本身确实代表了这种关系的一个“终点”。在这种情况下,从“位置”到“人物”的后向关系是'person_set' – 2011-04-13 01:53:59

+0

我明白了,我很感激帮助。 Django沉迷于“应该” - 如果你按照自己的方式做事,它会让事情变得简单。我猜我在问什么,为什么在这里我有一个类强制的差异,我猜这是关系的载体?大多数的设计决策对我来说都是有意义的 - 这个不是,这可能比框架更适合我,但是... – jal 2011-04-14 19:18:11

相关问题