alan
alan

Reputation: 4447

Django: Many-to-many with through vs 2x one-to-many

Reading, the Django docs on many-to-many relationships when you need an extra field on the intermediary table, it's not clear to me what you gain by defining the relationship as many-to-many vs just having a foreign key to the intermediary model in each of your models.

For instance, in the example here: https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany

Why bother with the ManyToManyField line? Does it allow you to refer to the relationship any differently? Does it change something in the admin?

Upvotes: 1

Views: 260

Answers (1)

Why bother with the ManyToManyField line: M2M fields are django fields which are useful for many model field interfaces like ModelAdmin or ModelForm (declaring fields, excluding, default widgets). It also generate helper methods like easy to access m2m managers and auto m2m saving in the admin.

Here's a quick example for what the field does automatically for the admin panel: you can't save a through model without the main object saved first. The admin handles this behavior with a save_m2m after the main object is saved automatically. If you did not use an m2m field, you'd have to code this kind of logic yourself.

I think you'd use this field when your project works with m2m fields but you just need a small amount of additional information. That way your code is virtually the same as a typical m2m relationship but when you need it, you can query the extra info.

Otherwise, adding a mere "date_added" field would require writing admin widgets, save_model hooks, ModelForm representation, etc.

You're right though that removing the m2m line with a through model won't make any database changes and you could ultimately replace the m2mfield functionality with the default ForeignKey reverse managers without much harm.

model.m2m_through_set.all() # this would work
model.m2m_through_set.create(target=target_instance)

Upvotes: 1

Related Questions