Django OneToMany
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开发者_如何学Go 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
You want a ForeignKey
to Order
from OrderLine
. Something like this:
from django.db import models
class Order(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class OrderLine(models.Model):
order = models.ForeignKey(Order, related_name='orderlines')
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
# Create a new order in the DB:
>>> order = Order.objects.create()
# Add a few items to this order:
>>> order.orderlines.create(name='Candied Yams')
<Candied Yams>
>>> order.orderlines.create(name='Minty loin of Lamb')
<Minty loin of Lamb>
# Get all items for this order:
>>> order.orderitems.all()
[<Candied Yams>, <Minty loin of Lamb>]
This is pretty well documented behavior :)
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
per order
.
Luckily, the act of creating a many-to-one link does this for you. Try this:
o = Order.objects.get(id=X)
lines = o.orderline_set.all()
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:
- Lower case
orderline
is deliberate, it is always lower case.
精彩评论