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
To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
¶ A many-to-many relationship refers to a relationship between tables in a database when a parent row in one table contains several child rows in the second table, and vice versa.
Just add str function in your foreign reference model Product.
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db. models. related module but is typically referenced from django.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With