2017-08-05 56 views
0

我試圖創建一個涉及產品,客戶和訂單的數據結構。客戶和產品是獨立的表格,而訂單參考產品和客戶。Django多對多數據模型

訂單表中的字段:

  1. 時間戳
  2. 客戶
  3. 產品以及數量

這是我試圖創造一個Django模型來實現這一目標:

from django.db import models 

class Customer(models.Model): 
    name = models.CharField(max_length=30) 
    latitude = models.FloatField(default=0) 
    longitude = models.FloatField(default=0) 

class Product(models.Model): 
    name = models.CharField(max_length=30) 
    weight = models.FloatField(default=0) 

class Order(models.Model): 
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE) 
    timestamp = models.DateTimeField(auto_now=True) 
    products = models.ManyToManyField(Product) 
    quantity = ? 

我該怎麼做cre吃了一個映射到特定產品的數量字段?替代模式也可以達到相同的效果。

+0

對於那些尋找如何使用Django管理這種模式,這應該幫助:https://stackoverflow.com/questions/6034047/one-to-many-inline-select-with-django-admin – NFern

回答

1

使用through在ManyToManyField。

from django.db import models 

class Customer(models.Model): 
    name = models.CharField(max_length=30) 
    latitude = models.FloatField(default=0) 
    longitude = models.FloatField(default=0) 

class Product(models.Model): 
    name = models.CharField(max_length=30) 
    weight = models.FloatField(default=0) 

class Order(models.Model): 
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE) 
    timestamp = models.DateTimeField(auto_now=True) 
    line_items = models.ManyToManyField(Product, through='OrderItem') 

class OrderItem(models.Model): 
    product = models.ForeignKey(Product) 
    order = models.ForeignKey(Order) 
    quantity, price, discount, ... 
+0

謝謝!這工作 – NFern

0

我會建議按順序包含產品及其數量的模型。像下面的東西。

class ProductOrder(models.Model): 
    product = models.ForeignKey(Product) 
    quantity = models.IntegerField() 

然後依次是:

class Order(models.Model): 
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE) 
    timestamp = models.DateTimeField(auto_now=True) 
    products = models.ManyToManyField(ProductOrder) 
+0

謝謝你,這是在正確的方向。什麼對我來說是「通過=」 – NFern