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.

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:

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:

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 5.x Django 4.2 Django 3.2 PostgreSQL MySQL SQLite