本文介绍了Django ManyToManyField错误对象没有属性'location_set'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这似乎是一个非常简单的问题,但是它正在杀死我。
This seems like a really trivial question, but it is killing me.
models.py
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')
从shell:
>>> 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'
我真的不是看到我失踪了
I'm really not seeing what I'm missing.
推荐答案
不应该使用 p.location.add()
? location_set
或< modelname> _set
是 。
Shouldn't you be using p.location.add()
? location_set
or <modelname>_set
is the default name for the reverse lookup for that model.
这篇关于Django ManyToManyField错误对象没有属性'location_set'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!