[Answer]-Django model with many-to-one or none relationship vs many-to-many through?

1👍

Libby. If I’m understanding your requirements, this seems like the simplest starting point — a many-to-one relationship using a ForeignKey field. (This is basically the same thing as lanzz’s suggestion.)

class User(models.Model):
  twitter_id = models.CharField(max_length=21, unique=True)
  twitter_name = models.CharField(max_length=55, unique=True)
  # ... other fields characterizing a Twitter account
  legislator = models.ForeignKey('Legislator', blank=True, null=True)

class Legislator(models.Model):
  last_name = models.CharField(max_length=17, blank=True)
  first_name = models.CharField(max_length=11, blank=True)
  # ... other fields characterizing a legislator

In your Python code, given a twitter account u and legislator l, you’d run u.legislator = l to associate a legislator with a twitter account. You could also express that as l.user_set.add(u), which makes more sense to me given these models.

Similarly, you’d use Legislator.user_setto access the RelatedManager for twitter accounts. This is what you’d loop over in a template or do additional queries against when you want to work with the related model (any/all related twitter accounts) instead of the one you have (a legislator).

There are a few more usage examples in the docs.

In the ForeignKey field, I set blank=True, null=True to make the relationship optional. Unless you specify otherwise in the field’s options, Django will create and use a legislator_id column in the User table to manage the relationship.

👤Brian

Leave a comment