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

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.