Friday, October 16, 2020

How to make recursive ManyToMany relationships through an intermediate model symmetrical

 

I've read the docs. I've read this question too, but the following code is not working as the Django docs describe.

If bill and ted are friends, bill.friends.all() should include ted,  and ted.friends.all() should include bill. This is not what Django does. ted's query is empty, while bill's query includes ted.
# people.models  from django.db import models      class Person(models.Model):      name = models.CharField(max_length=255)      friends = models.ManyToManyField("self",                                       through='Friendship',                                       through_fields=('personA', 'personB'),                                       symmetrical=True,                                       )        def __str__(self):          return self.name      class Friendship(models.Model):      personA = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='personA')      personB = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='personB')      start = models.DateField(null=True, blank=True)      end = models.DateField(null=True, blank=True)        def __str__(self):          return ' and '.join([str(self.personA), str(self.personB)])



>>> import django
>>> django.__version__
'3.1.2' >>>
from people.models import Person, Friendship >>> bill = Person(name='bill') >>> bill.save() >>> ted = Person(name='ted') >>> ted.save() >>> bill_and_ted = Friendship(personA=bill, personB=ted) >>> bill_and_ted.save() >>> bill.friends.all() <QuerySet [<Person: ted>]> >>> ted.friends.all() <QuerySet []> >>> ted.refresh_from_db() >>> ted.friends.all() <QuerySet []> >>> ted = Person.objects.get(name='ted') >>> ted.friends.all() <QuerySet []>

Can someone please show me how to make this behave as expected.

No comments:

Post a Comment