我的问题:
我希望我的客户能够将多个不同的产品连接到一个合同,并且列出所有附加到合同的产品的代码感觉很脏。是否可以将不同的产品对象连接到一个合同?
我的模型
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帮助做这在某种理智的方式是什么。
我不介意把所有的东西都抽象出来,只是为了得到更干净的代码。
这看起来是正确的,我现在会深入研究它,谢谢! – schmilblick 2010-12-19 09:15:22
这完全正确! :) 谢谢!!今天我又了解了内容类型框架,非常感谢! – schmilblick 2010-12-20 17:30:37
嘿,恭喜!我对解决方案非常好奇 - 你是否逐字逐句使用了片段?小心分享? :d – 2010-12-20 19:44:41