There are quite a few places to suggest using ForeignKey
for one-to-many or many-to-one relationship, but I am struggling to understand how this will work without reversing dependency.
For example:
I have these 2 apps, 'settlements' and 'payments', ideally, settlements don't need to know about payments because payment records are created after settlements have been made, and a payment record can contain multiple settlements.
settlements model:
class Settlement(models.Model):
...
payments model:
class Payment(models.Model):
settlements = models.ManyToManyField('Settlement')
....
This brings a fundamental schema caveat, that settlement can belong to multiple payments, which should not happen.
To enforce a settlement cannot belong to more than one payment record, I will have to put the payment foreignkey
in Settlement:
settlements model:
class Settlement(models.Model):
payment = models.ForeignKey('Payment')
...
payments model:
class Payment(models.Model):
....
While this enforce the schema validity, but seems the dependency has reversed, now that settlement needs to know about payment, just made these 2 apps tightly coupled. Also I need to create a settlement record with payment field being null, create the payment record, then go back to the settlement record to link up the payment record, this seems wrong.
belongs to
-- Settlement 1, 3, and 9 belong to Payment 4.