Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 398
paweloque Avatar asked Dec 30 '10 13:12

paweloque


People also ask

How do I add a one to many relationship in Django?

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).

What is a many-to-many relationship Django?

¶ 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.

How can I get ForeignKey ID in Django?

Just add str function in your foreign reference model Product.

What is a ForeignKey in Django?

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.


1 Answers

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 :)

like image 170
elo80ka Avatar answered Sep 25 '22 08:09

elo80ka