如何从ManyToMany联接表中检索信息

时间:2019-04-25 20:24:33

标签: python django django-models python-3.7

我有一个具有以下模型的Django应用程序:

class Topic(models.Model):
    key = models.CharField(max_length=255, primary_key=True)


class Person(models.Model):
    first_name = models.CharField(max_length=255)
    interests = models.ManyToManyField(Topic, through='Interest')


class Interest(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    source = models.ForeignKey(TopicSource, on_delete=models.CASCADE)

兴趣表可增强人与主题之间的多对多关系。但是,此联接表包含额外的信息,该信息是信息的来源。

从外壳中检索一个人感兴趣的主题列表非常容易:

>>> from app.models import Person, Topic, Interest
>>> p1 = Person.objects.all()[0]
>>> p1.interests.all()
<QuerySet [<Topic: discrete_mathematics>, <Topic: statistics>]>

但是,似乎无法从联接表中检索额外的信息:

>>> [item.source for item in p1.interests.all()]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 1, in <listcomp>
AttributeError: 'Topic' object has no attribute 'source'

这很有意义,因为interests属性指向Topicinterests = models.ManyToManyField(Topic, through='Interest')

是否有一种方法还可以检索source

0 个答案:

没有答案