Accessing django oscar product attributes

3.1k Views Asked by At

I want to access a product attribute's value. I have defined a product attribute with code weight and type float. In my views I'm trying to access it as below:

def red(request):
    basket = request.basket
    weight_total = 0
    for line in basket.all_lines():
        weight = line.product.attributes.get(code = 'weight')
        weight_total += weight.productattributevalue

It doesn't work and gives error:

'ProductAttribute' object has no attribute 'productattributevalue'

I tried looking into oscar's model but couldn't find the solution. Please help.

2

There are 2 best solutions below

0
On BEST ANSWER

I would recommend copying the Django Oscar shipping/scales.py Scale class weigh_product() method.

In there, they use the 'value' property of the product's 'attribute_values' property.

try:
    attr_val = product.attribute_values.get( # Using 'attribute_values'
        attribute__code=self.attribute)      # Use your own code of 'weight'
except ObjectDoesNotExist:
    if self.default_weight is None:          # You can set a default weight.
        raise ValueError("No attribute %s found for product %s"
                         % (self.attribute, product))
    weight = self.default_weight
else:
    weight = attr_val.value                  # << HERE. using 'value' property
1
On

To get or set an attribute by code, just do:

product.attr.code

for example, if the code of your attribute is "weight":

product.attr.weight = 125

I found that example in the code for oscar.apps.catalogue.product_attributes (django-oscar 1.4) and it works both in python and in templates.