无法访问Django-Oscar中产品的价格?

时间:2015-08-11 10:38:49

标签: python django django-oscar

尝试使用Docs访问产品的价格。但是获得属性错误。

>>> from oscar.apps.partner import strategy, prices
>>> from oscar.apps.catalogue.models import *
>>> product = Product.objects.get(pk=1)
>>> info = strategy.fetch_for_product(product)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'fetch_for_product'

要查看策略的所有属性

  >>> dir(strategy)
  >>> ['Base', 'D', 'Default', 'DeferredTax', 'FixedRateTax', 'NoTax', 'PurchaseInfo', 
    'Selector', 'StockRequired', 'Structured', 'UK', 'US', 'UseFirstStockRecord', 
'__builtins__', '__doc__', '__file__', '__name__',
 '__package__', 'availability', 'namedtuple', 'prices']

因此fetch_for_product不属于策略属性。现在我如何获取特定产品的价格?

2 个答案:

答案 0 :(得分:7)

您在上面导入的是策略模块。您想要的是战略对象。获得策略的最简单方法是向策略选择器询问一个:

from oscar.apps.partner.strategy import Selector

selector = Selector()
strategy = selector.strategy(request=..., user=...)
purchase_info = strategy.fetch_for_product(product=...)
price = purchase_info.price

选择器非常有用,因为它允许您根据上下文使用不同的策略(特定用户,来自特定国家/地区的请求等)。在您自己的商店中,您可以使用自己的实现覆盖Selector,默认情况下会返回Default strategy

有关详细信息,请参阅the docs

答案 1 :(得分:0)

您可以使用自定义字段制作新的序列化程序,以使用SerializeMethodField加载包含价格,主图像和标题的类别产品。

from rest_framework import serializers

from oscar.apps.partner.strategy import Selector

class ProductsSerializer(serializers.ModelSerializer):
    price = serializers.SerializerMethodField()
    availability = serializers.SerializerMethodField()
    images = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields= ('id', 'title','availability', 'images', 'price',)

    def get_price(self, obj):
        strategy = Selector().strategy()
        price = vars(strategy.fetch_for_product(obj).price)
        price['final'] = price['excl_tax'] + price['tax']
        return price

    def get_availability(self, obj):
        strategy = Selector().strategy()
        availability = vars(strategy.fetch_for_product(obj).availability)
        try:
            return availability['num_available']
        except KeyError:
            return -1

    def get_images(self, obj):
        try:
            return ['https://127.0.0.1:8000/'+str(obj.primary_image().original)]
        except AttributeError:
            return []