2010-06-09 101 views
0

概念:django造型

饮料是由部件组成。例如。 10毫升伏特加。在某些收据中,组件非常特别(芬兰伏特加10毫升),有些则不是(任何伏特加10毫升)。

我不知道如何建模一个组件来解决这个问题 - 库存我有特定的产品,可以满足更多的需求。

模型现在是:

class Receipt(models.Model): 
    name = models.CharField(max_length=128) 
    (...) 
    components = models.ManyToManyField(Product, through='ReceiptComponent') 

    def __unicode__(self): 
    return self.name 

class ReceiptComponent(models.Model): 
    product = models.ForeignKey(Product) 
    receipt = models.ForeignKey(Receipt) 
    quantity = models.FloatField(max_length=9) 
    unit = models.ForeignKey(Unit) 
    class Admin: 
    pass 
    def __unicode__(self): 
    return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive 

class Product(models.Model): 
    name = models.CharField(max_length = 128) 
    (...) 
    class Admin: 
    pass 
    def __unicode__(self): 
    return self.name 

class Stock(Store): 
    products = models.ManyToManyField(Product) 
    class Admin: 
    pass 
    def __unicode__(self): 
    return self.name 

我想想做一些表,加入真正的产品(股票)与抽象产品(receiptcomponent)。但也许有简单的解决方案?

回答

1

我想我会采用更复杂的方法,使用产品对象在层次结构中的树结构。可能有一个节点称为“酒精”,孩子节点为“伏特加”,“威士忌”,“啤酒”。和“伏特加”有子节点“芬兰伏特加”和“俄罗斯伏特加”

如果没有“完成伏特加”的股票,首先检查它的所有孩子(“绝对伏特加”,...),然后遍历其兄弟姐妹(“俄罗斯伏特加酒”),然后是其父节点(以相反的顺序)(“伏特加酒”,“酒精”),直到发现有库存。 num_in_stock将是产品表中的整数字段。

在谷歌代码http://code.google.com/p/django-mptt/上有一个众所周知的伟大工作应用程序mptt(Modified Pre-ordered Tree Traversal),这对django中的树木非常有用。

+0

这真的很酷的应用程序。在我的情况下完美。谢谢! – 2010-06-11 09:45:51