2

我想访问产品属性的值。我已经用 codeweight和 type定义了一个产品属性float。在我看来,我正在尝试按如下方式访问它:

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

它不起作用并给出错误:

'ProductAttribute' object has no attribute 'productattributevalue'

我试图研究 oscar 的模型,但找不到解决方案。请帮忙。

4

2 回答 2

5

我建议复制 Django Oscar shipping/scales.py Scale 类weight_product() 方法。

在那里,他们使用产品的'attribute_values'属性的'value'属性。

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
于 2014-12-21T17:06:38.943 回答
3

要通过代码获取或设置属性,只需执行以下操作:

product.attr.code

例如,如果您的属性代码是“重量”:

product.attr.weight = 125

我在 (django-oscar 1.4) 的代码中找到了该示例,oscar.apps.catalogue.product_attributes它在 python 和模板中都有效。

于 2017-04-14T06:10:24.667 回答