Skip to main content
 首页 » 编程设计

python之Oscar 提供应用覆盖福利功能冲突错误

2024年11月24日8落叶

我用的是 Oscar 1.6.4 版本。我想覆盖 oscar.app.offer.benefits.py 中的 PercentageDiscountBenefit。但是发生冲突错误。如何覆盖此功能?

from oscar.core.loading import get_classes 
 
CorePercentageDiscountBenefit, CoreAbsoluteDiscountBenefit = get_classes('offer.benefits', ['PercentageDiscountBenefit', 'AbsoluteDiscountBenefit']) 
 
 
class PercentageDiscountBenefit(CorePercentageDiscountBenefit): 
 
    def apply(self, basket, condition, offer, discount_amount=None, 
              max_total_discount=None): 
 
        print( 
            "\n\n\n\n", 
            "PRINT SOMETHING", 
            "\n\n\n\n", 
        ) 
        return super().apply(basket, condition, offer, discount_amount, 
              max_total_discount) 
 
 
class AbsoluteDiscountBenefit(CoreAbsoluteDiscountBenefit): 
 
    def apply(self, basket, condition, offer, discount_amount=None, 
              max_total_discount=None): 
 
        print( 
            "\n\n\n\n", 
            "PRINT SOMETHING", 
            "\n\n\n\n", 
        ) 
        return super().apply(basket, condition, offer, discount_amount, 
              max_total_discount) 

错误日志

RuntimeError at /basket/ 
 
Conflicting 'percentagediscountbenefit' models in application 'offer': <class 'oscar.apps.offer.benefits.PercentageDiscountBenefit'> and <class 'oscar_apps.offer.benefits.PercentageDiscountBenefit'>. 
 
Request Method:     GET 
Request URL:    http://localhost:8000/basket/ 
Django Version:     1.11.9 
Exception Type:     RuntimeError 
Exception Value:     
 
Conflicting 'percentagediscountbenefit' models in application 'offer': <class 'oscar.apps.offer.benefits.PercentageDiscountBenefit'> and <class 'oscar_apps.offer.benefits.PercentageDiscountBenefit'>. 
 
Exception Location:     /home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/lib/python3.5/site-packages/django/apps/registry.py in register_model, line 224 
Python Executable:  /home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/bin/python 
Python Version:     3.5.2 
Python Path:     
 
['/home/seyidov/PycharmProjects/Backend/embahome-backend', 
 '/home/seyidov/PycharmProjects/Backend/embahome-backend', 
 '/usr/lib/python35.zip', 
 '/usr/lib/python3.5', 
 '/usr/lib/python3.5/plat-x86_64-linux-gnu', 
 '/usr/lib/python3.5/lib-dynload', 
 '/home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/lib/python3.5/site-packages', 
 '/home/seyidov/Documents/Programs/pycharm-2018.2.4/helpers/pycharm_matplotlib_backend', 
 '/home/seyidov/PycharmProjects/Backend/embahome-backend'] 

请您参考如下方法:

您不能以这种方式覆盖福利等级。如果您想创建一个将不同逻辑应用于核心利益的自定义利益,您需要创建自己的类,它是核心 Benefit 模型的代理:

from oscar.apps.offer import models 
 
class CustomPercentageDiscountBenefit(models.Benefit): 
 
    class Meta: 
        proxy = True 
 
    def apply(self, basket, condition, offer, discount_amount=None, max_total_discount=None): 
        # Apply your benefit here 

这在 more detail in the documentation 中有解释.