About Many-to-many Relationships to Self

In Django, Many-to-many relationships to self are symmetrical by default and create two database entries for each relation.

1
2
3
class Location(models.Model):
    name = models.CharField(max_length=200)
    related_locations = models.ManyToManyField("self", blank=True)

This means, that these would work out of the box:

1
2
location1.related_locations.filter(pk=location2.pk).exists()
location2.related_locations.filter(pk=location1.pk).exists()

And both location1 and location2 would be in the following query:

1
2
3
locations_with_related_locations = Location.objects.annotate(
    related_locations_count=models.Count("related_locations"),
).filter(related_locations_count__gt=0)

Tips and Tricks Programming Architecture Django 4.2 Django 3.2 Django 2.2 Django 1.11 Django 1.8