Python 是否可以将不同的产品对象连接到一个合同?
我的问题:Python 是否可以将不同的产品对象连接到一个合同?,python,django,django-models,application-design,Python,Django,Django Models,Application Design,我的问题: 我希望我的客户能够将许多不同的产品连接到一个合同中,并且列出合同中所附所有产品的代码会让人感觉脏兮兮的 我的车型 class Contract(models.Model): # The contract, a customer can have many contracts customer = models.ForeignKey(Customer) class Product(models.Model): # A contract can have ma
我希望我的客户能够将许多不同的产品连接到一个合同中,并且列出合同中所附所有产品的代码会让人感觉脏兮兮的 我的车型
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")
因此,我可以像这样获取每个特定产品(伪ish代码):
列出所有“真实”产品,而不仅仅是baseproduct实例
我需要什么帮助建议以某种理智的方式来做这件事。
我不介意把所有东西都抽象成一堆步骤,只是为了得到更干净的代码。如果你知道客户永远不会订购
产品,为什么不把它做成一个抽象模型,然后自己排序呢?在这一点上,访问用户的书籍、汽车或房屋清洁变得很容易,因为您只需使用c.book\u set.all()
,c.car\u set.all()
,等等
如果你想要,比如说,一份合同所附的所有产品的列表,你就必须自己进行排序,但是如果你正在寻找的是这个列表,那么编写一个排序的包装器来将所有内容放入列表并不难。另一个堆栈问题看起来直接相关——也许会有帮助
>>> Product.objects.all()
[<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...]
>Product.objects.all()
[, , ...]
具体地说,该代码段具有子类模型mean
salar(mean)
祝你好运 合同将如何包含相互不同的书籍、汽车和房屋清洁对象?简单:def product_set(self):products=self.Book_set.all()+self.Car_set.all()+self.house cleaning_set.all()返回已排序(产品,lambda i:i.created_date)
因此每次添加新产品时,我必须添加另一个c.newproduct_set.all()?我对那个解决方案不满意。。。我是不是太挑剔了?:)好吧,最终取决于你——我就是这么做的,但你可以自由地做你想做的事。您可能希望了解Django模型如何跟踪其相关项-您可以进行一些自省来为您处理c.newproduct_set.all()部分。这完全正确!:)谢谢今天我再次学习了contenttypes框架:非常感谢!恭喜你!我对这个解决方案非常好奇——你是逐字使用这个片段的吗?愿意分享吗D
>>> Product.objects.all()
[<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...]