我知道这个问题似乎已经回答了好几次,但是我发现的任何答案都没有给我任何指向我所面临问题的指针。
我在Django应用程序中有3种模型:
class Person(models.Model):
name = model.CharField(...)
class Topic(models.Model):
key = model.CharField(...)
class Interest(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
comment = models.CharField(...)
Person.interests = models.ManyToManyField(Topic, through="Interest")
views.py
声明如下:
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'people_list'
def get_queryset(self):
return Person.objects.all()
index.html
如下所示:
{% for person in people_list %}
<tr>
<td>{{ person.name }}</td>
<td>
<ul>
{% for interest in person.interests.all %}
<li>{{ interest }}</li>
{% empty %}
No interest found
{% endfor %}
</ul>
</td>
</tr>
{% endfor %}
令人惊讶的是,当管理站点清楚地显示了所有人的兴趣时,该视图将为每个人返回“未发现兴趣”。
Person.objects.all()
中的views.py
似乎没有从数据库中加载相关对象。
使用外壳时,我得到以下结果:
Python 3.7.2 (default, Feb 12 2019, 08:15:36)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from app.models import Person, Topic, Interest
>>> person = Person.objects.all()[0]
>>> person.interests
<django.db.models.fields.related.ManyToManyField>
>>> person.interests.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'ManyToManyField' object has no attribute 'all'
答案 0 :(得分:2)
您必须在类定义中定义字段。这应该起作用:
class Person(models.Model):
name = model.CharField(...)
interests = models.ManyToManyField('Topic', through='Interest')