Jonah Bishop
Jonah Bishop

Reputation: 12581

Uniquely identifying ManyToMany relationships in Django

I'm trying to figure out how best to uniquely identify a ManyToMany relationship in my Django application. I have models similar to the following:

class City(models.Model):
    name = models.CharField(max_length=255)
    countries = models.ManyToManyField('Country', blank=True)

class Country(models.Model):
    name = models.CharField(max_length=255)
    geo = models.ForeignKey('Geo', db_index=True)

class Geo(models.Model):
    name = models.CharField(max_length=255)

I use the ManyToManyField type for the countries field because I want to avoid city name duplication (i.e. there may be a city name like "Springfield" that appears in multiple locations).

In another place in my application, I want to be able to uniquely identify the city-country-geography relationship. That is, I need to know that a user whose city is "Springfield" resides in the United States, versus Canada, for example. As a result, I need to know which of the ManyToManyField relationships my city maps to. My user looks something like this:

class MyUser(models.Model):
    # ... other fields ...
    city = models.ForeignKey('City', db_index=True, blank=True, null=True)

This setup clearly does not capture the relationship between city and country properly. What's the best way to capture the unique relationship? Would I use a custom through-table with an AutoField acting as a key, and change my user to point to that through-table?

Upvotes: 2

Views: 117

Answers (1)

Adam Hopkins
Adam Hopkins

Reputation: 7102

I think your idea of a through table is the right approach. Then, I would add a unique_together('city', 'country') into the Meta.

I don't think there is a need for an AutoField

Upvotes: 2

Related Questions