Unable to access the product price in Django-Oscar?

Trying to access the price of a product using Docs . But getting the attribute error.

>>> 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' 

To see all the attributes of a strategy, I do

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

So fetch_for_product is not included in the attributes of the strategy. Now, how can I access the price of a particular product?

+4
source share
2 answers

What you import above is a strategic module . Instead, you want to use the object strategy. The easiest way to get a strategy is to ask a strategy selector for one:

 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 

The selector is useful because it allows you to use different strategies depending on the context (specific user, request coming from a specific country, etc.). In your own store, you will override Selector your own implementation, by default it will return the Default strategy.

See documents for more details.

+7
source

You can create a new serializer with a custom field to load a product category with price, main image and name using 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 [] 
0
source

All Articles