Django一对多的领域没有反转依赖 [英] Django one-to-many field without reversing dependency
问题描述
有很多地方建议使用 ForeignKey
进行一对多或多对一的关系,但我很难理解这将如何工作没有反转依赖关系。
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.
例如:
我有这两个应用程序,结算和付款理想情况下,定居点不需要知道付款,因为支付记录是在结算后创建的,支付记录可以包含多个结算单。
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.
结算模型:
class Settlement(models.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.
执行结算不能属于更多一个支付记录,我将不得不在结算中支付 foreignkey
:
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')
...
付款模式:
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.
推荐答案
我的同事发现这个项目:
A colleague of mine found this project:
https://github.com/adsworth/django-onetomany
它在manytomany关系。
It's adding a unique together constraint in the manytomany relationship.
这篇关于Django一对多的领域没有反转依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!