2010-12-16 63 views
0

我的问题
我希望我的客户能够将多个不同的产品连接到一个合同,并且列出所有附加到合同的产品的代码感觉很脏。是否可以将不同的产品对象连接到一个合同?

我的模型

class Contract(models.Model): 
    # The contract, a customer can have many contracts 
    customer = models.ForeignKey(Customer) 


class Product(models.Model): 
    # A contract can have many different products 
    contract = models.ForeignKey(Contract) 
    start_fee = models.PositiveIntegerField() 

# A customer may have ordered a Car, a Book and a HouseCleaning, 
# 3 completly different Products 

class Car(Product): 
    brand = models.CharField(max_length=32) 

class Book(Product): 
    author = models.ForeignKey(Author) 

class HouseCleaning(Product): 
    address = models.TextField() 

要列出所有连接到合同的产品,代码看起来是这样的:

c = Contract.objects.get(pk=1) 
for product in c.product_set.all(): 
    print product.book # Will raise an Exception if this product isnt a Book 

我找不到任何理智的方法来找出什么样的产品是一种产品!

我目前的解决方案
我已经解决它像这样...但是这整个混乱的感觉......错了。我会很高兴任何指向正确方向的指针。

class Product(models.Model): 
    # (as above + this method) 

    def getit(self): 
     current_module = sys.modules[__name__] 
     classes = [ obj for name, obj in inspect.getmembers(current_module) 
        if inspect.isclass(obj) and Product in obj.__bases__ ] 

     for prodclass in classes: 
      classname = prodclass.__name__.lower() 
      if hasattr(self, classname): 
       return getattr(self, classname) 

     raise Exception("No subproduct attached to Product") 

这样我就可以提取每个特定的产品是这样的(伪上下的代码):

c = Contract.objects.get(pk=1) 
for product in c.product_set.all(): 
    print product.getit() 

列出所有的“真实”的产品,而不仅仅是baseproduct实例。

我需要
Sugggestions帮助做这在某种理智的方式是什么。
我不介意把所有的东西都抽象出来,只是为了得到更干净的代码。

回答

1

这个其他堆栈的问题看起来直接相关 - 也许它会帮助吗?

>>> Product.objects.all() 
[<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...] 

Subclassed django models with integrated querysets

具体来说,段已子类车型MealSalad(Meal)

http://djangosnippets.org/snippets/1034/

祝你好运!

+0

这看起来是正确的,我现在会深入研究它,谢谢! – schmilblick 2010-12-19 09:15:22

+0

这完全正确! :) 谢谢!!今天我又了解了内容类型框架,非常感谢! – schmilblick 2010-12-20 17:30:37

+0

嘿,恭喜!我对解决方案非常好奇 - 你是否逐字逐句使用了片段?小心分享? :d – 2010-12-20 19:44:41

0

如果您知道客户永远不会订购Product,为什么不把它作为抽象模型,然后就自己排序呢?在这一点上访问用户的书籍,汽车或房屋清洁变得容易,因为您只需使用c.book_set.all(),c.car_set.all()等等。

你不得不做整理自己,如果你想,说,附属于合同的所有Product s的名单 - 但它并不难写一个sorted包装把一切都变成清单你,如果这就是您正在寻找。

+0

合同将包含书本,汽车和房屋清洁物品,这些物品彼此不同? – 2010-12-16 18:08:44

+0

Easy:'def product_set(self):products = self.book_set.all()+ self.car_set.all()+ self.housecleaning_set.all()return sorted(products,lambda i:i.created_date)' – girasquid 2010-12-16 18:11:11

+0

So每次添加新产品时,我都需要添加另一个c.newproduct_set.all()?我对这个解决方案感到不舒服...我是否太挑剔?:) – schmilblick 2010-12-17 10:05:23

相关问题