我的问题:
我希望我的客户能够将许多不同的产品连接到一个合同,并且列出附加到合同的所有产品的代码感觉很脏。
我的模特
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 实例。
我需要什么帮助
才能以某种理智的方式做到这一点。
我不介意将所有内容抽象出一堆步骤,只是为了获得更清晰的代码。