2009-11-11 78 views
4

在完成Django教程之后,我正在尝试构建一个非常简单的开票应用程序。内联编辑Django中的ManyToMany关系

我想将多个产品添加到发票中,并在Django管理员的发票表单中指定每个产品的数量。现在,如果我拥有同一产品的不同数量,则必须创建一个新的Product对象。

现在我的模型看起来像这样(公司与客户机型离开了):

class Product(models.Model): 
    description = models.TextField() 
    quantity = models.IntegerField() 
    price = models.DecimalField(max_digits=10,decimal_places=2) 
    tax = models.ForeignKey(Tax) 

class Invoice(models.Model): 
    company = models.ForeignKey(Company) 
    customer = models.ForeignKey(Customer) 
    products = models.ManyToManyField(Product) 
    invoice_no = models.IntegerField() 
    invoice_date = models.DateField(auto_now=True) 
    due_date = models.DateField(default=datetime.date.today() + datetime.timedelta(days=14)) 

我猜的数量应被排除在产品型号的,但我怎么能做出一个字段为它发票模型?

回答

9

您需要稍微改变模型结构。如您所知,该数量不属于产品型号 - 它属于产品和发票之间的关系

要做到这一点在Django,你可以使用一个ManyToMany relationship with a through table

class Product(models.Model): 
    ... 

class ProductQuantity(models.Model): 
    product = models.ForeignKey('Product') 
    invoice = models.ForeignKey('Invoice') 
    quantity = models.IntegerField() 

class Invoice(models.Model): 
    ... 
    products = models.ManyToManyField(Product, through=ProductQuantity) 
+0

谢谢!这正是我所期待的。 – vorpyg 2009-11-12 18:17:36