Search code examples
pythondjangodjango-oscar

Can't access price of a Product in Django-Oscar?


Trying to access the price of a product, Using Docs. But getting 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 attributes of 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 in attributes of strategy. Now how can I access the price of a particular product?


Solution

  • What you import above is the strategy module. What you want is the strategy object instead. The easiest way to obtain the strategy is to ask the 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 as it allows you to use different strategies depending on the context (a particular user, request coming from a particular country etc.). In your own store you would override the Selector with your own implementation, by default it will return the Default strategy.

    See the docs for more information.