2011-04-11 67 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