0

I have a Django application with the following models:

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)

The many-to-many relationship between a person and a topic is enforced with the interest table. However, this joining table contains an extra information which is the source of the information.

From the shell, it is quite easy to retrieve the list of topics a person is interested in:

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

But, it does not seem possible to retrieve the extra information from the joining table:

>>> [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'

It makes sense since the interests attribute points to the Topic (interests = models.ManyToManyField(Topic, through='Interest'))

Is there a way to also retrieve the source?

E. Jaep
  • 2,095
  • 1
  • 30
  • 56

0 Answers0