Django 一对多
我正在 django 中实现一个小型电子商店应用程序。 我的问题涉及对具有多个 OrderLines 的 Order 进行建模: 如何使用可直接从订单访问的 OrderLines 来建模 Order 到 OrderLines 的关系,即
Order
def addOrderLine
def allOrderLines
我想从 Order 访问 OrderLines 而不必直接从数据库获取它们。 Django 提供了定义ForeignKeys 的可能性,但这并不能解决我的问题,因为我必须定义以下内容:
class OrderLine(models.Model):
order = models.ForeignKey(Order)
使用此定义,我必须直接从数据库而不是通过Order 获取OrderLines。
我可能会使用这个定义并提供 Order
级别的方法。但是,这不起作用,因为如果我在 models.py
文件中的 OrderLine
上方定义 Order
,则 Order
看不到 OrderLines
I'm implementing a small e-shop application in django.
My question concerns modelling an Order with many OrderLines:
How to model the Order to OrderLines relationship with the OrderLines accessible directly from the Order, i.e.
Order
def addOrderLine
def allOrderLines
I want to access the OrderLines from the Order and not have to get them from the db directly. Django offers the possibility to define ForeignKeys, but this doesn't solve my problem, because I'd have to define the following:
class OrderLine(models.Model):
order = models.ForeignKey(Order)
With this definition I'd have to fetch the OrderLines directly from the db and not through the Order.
I'm might use this definition and provide methods on the Order
level. This, however, doesn't work because if I define the Order
above the OrderLine
in the models.py
file, the Order
doesn't see the OrderLines
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一个
ForeignKey
从OrderLine
进行Order
。像这样的东西:这是记录得很好 行为:)
You want a
ForeignKey
toOrder
fromOrderLine
. Something like this:This is pretty well documented behavior :)
如果我理解正确的话,您正在寻找多对一的逆过程,即为您提供每个
订单
的一组所有orderlines
的访问器。幸运的是,创建多对一链接的行为可以为您做到这一点。试试这个:
行现在应该包含整个链接订单行集。它似乎没有被广泛记录,但是如果您阅读 many-to 中的示例代码-仔细阅读一个文档,您将看到此功能一直在使用。
注意:
orderline
是故意的,它始终是小写的。If I understand this correctly you're looking for the inverse of the many to one i.e. an accessor that provides you with a set of all
orderlines
perorder
.Luckily, the act of creating a many-to-one link does this for you. Try this:
lines should now contain the entire set of linked order lines. It doesn't seem to be widely documented, but if you read the example code in the many-to-one documentation closely, you'll see this functionality used all the time.
Notes:
orderline
is deliberate, it is always lower case.