Django should have OneToManyField

By | September 17, 2014

A bit of background here about ForeignKey (many to one):

If you have Order and OrderItem models, your order FK is in OrderItem model, from OrderItem model point of view, it’s Many OrderItem to One Order, in other words ManyToOne. What this implies is you need to have Order records before OrderItem records.

Now, why we need one to many:

What if you have 2 different apps, say Settlement and Payment, which a payment can have multiple settlements, but settlements can only belong to one payment. Logically Payment app is built on top of Settlement app, in other words Settlement app doesn’t need to know about Payment app. But to make the constraint to work, you need to put the Payment foreignkey into the Settlement model (surely this makes sense in DB schema, but not in programming domain), which now Settlement app is required to know about the Payment app.

Not only the dependency is reversed, now you need to have payment record created before settlement record, WTF? Oh certainly you have the payment FK set to nullable, but then you will have an extra step to set the relationship.

Luckily there is a 3rd party package that kind of solve this problem through ManyToMany relationship by adding unique constraint on the right hand column, but unluckily if you ever want to roll back to the normal ManyToManyField, the migration doesn’t remove the additional constraints that introduced by this package. See django ticket.

For relevant information:

http://stackoverflow.com/questions/25635408/django-one-to-many-field-without-reversing-dependency

http://blog.amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/

One thought on “Django should have OneToManyField

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.