2016-07-24 65 views
0

我對電子商店django骨架稀薄。Django:項目可擴展折扣計算

# models.py 
class Category(models.Model): 
    name = models.CharField() 
    discount = models.DecimalField() 


class Product(models.Model): 
    name = models.CharField() 
    price = models.DecimalField() 
    category = models.ForeignKey(Category) 
    discount = models.DecimalField() 

現在我需要計算產品最終折扣。它的產品和類別的折扣最大的一個:

class Product(models.Model): 
    ... 
    def get_final_discount(self): 
     return max([self.discount, self.category.discount]) 

但現在我需要我的模型與品牌模式擴展。品牌模型有自己的折扣,所以我需要修改Product.get_final_discount()方法來考慮品牌在最終產品價格計算中的折扣。

問題:實施不違反開閉原則的最終產品折扣方法的最佳方法是什麼?

+0

你說的「我需要我的模型與品牌型號擴展」是什麼意思?您是否想將外鍵添加到品牌模型或品牌模型中的類別,產品或兩者?或者你想要子類品牌模型? –

+0

@VladimirDanilov在這種情況下,我需要將Product從Product添加到Brand。此外,我希望可以自由地從產品添加相同的FK到具有自己折扣的模型。 –

回答

0

您可以創建一個方法來檢查您的模型的所有字段是否滿足2個條件:1.)該字段爲ForeignKey; 2.)它引用的模型具有discount屬性。如果兩者均爲真,則該方法將reference_model.discount的值添加到一系列折扣。這個方法可以用在你的max()函數中。

這裏有一個工作示例:

from django.db import models 


class Category(models.Model): 
    name = models.CharField(max_length=255) 
    discount = models.DecimalField(decimal_places=2, max_digits=10) 


class Brand(models.Model): 
    name = models.CharField(max_length=255) 
    discount = models.DecimalField(decimal_places=2, max_digits=10) 


class Product(models.Model): 
    name = models.CharField(max_length=255) 
    price = models.DecimalField(decimal_places=2, max_digits=10) 
    category = models.ForeignKey(Category) 
    brand = models.ForeignKey(Brand) 
    discount = models.DecimalField(decimal_places=2, max_digits=10) 

    def get_all_discounts(self): 
     all_fields = self._meta.get_fields() 
     discounts = [] 
     for field in all_fields: 
      if field.get_internal_type() == 'ForeignKey': 
       field_ref = getattr(self, field.name) 
       if hasattr(field_ref, 'discount'): 
        discounts.append(field_ref.discount) 

     return discounts 

    def get_final_discount(self): 
     return max(self.get_all_discounts())