Uniquely identifying ManyToMany relationships in Django
<p>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:</p>

<pre><code>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)
</code></pre>

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

<p>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 <code>ManyToManyField</code> relationships my city maps to. My user looks something like this:</p>

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

<p>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 <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ManyToManyField.through" rel="nofollow">through-table</a> with an <code>AutoField</code> acting as a key, and change my user to point to that through-table?</p>

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

<p>I don't think there is a need for an <code>AutoField</code></p>

python django orm