使用Django Oscar的get_value_by_attribute()获取产品属性值报错求助
get_value_by_attribute() in Django Oscar Let me break down what's going wrong here and how to fix it:
The core issue is that the get_value_by_attribute() method doesn't accept the attribute's name string (like "Brand") as an argument. Instead, it expects either:
- A
ProductAttributemodel instance, or - The integer ID of the
ProductAttribute
That's why you're seeing the ValueError: invalid literal for int() with base 10: 'Brand' error — the method is trying to convert your string "Brand" into an integer ID, which obviously fails.
Here are a few straightforward ways to get the attribute value you want:
Method 1: Fetch the ProductAttribute instance first
You can look up the ProductAttribute by its name, then pass that object to the method:
from oscar.apps.catalogue.models import ProductAttribute # Get the Brand attribute instance brand_attribute = ProductAttribute.objects.get(name="Brand") # Now retrieve the value for your product brand_value = child_product.attr.get_value_by_attribute(attribute=brand_attribute) # To get the actual value (e.g. "Britania"), access the .value attribute print(brand_value.value)
Method 2: Use the attribute's integer ID
If you know the ID of the "Brand" attribute (you can find this via child_product.attr.get_all_attributes() or your admin panel), you can pass it directly:
# Replace 1 with the actual ID of your Brand attribute brand_value = child_product.attr.get_value_by_attribute(attribute=1) print(brand_value.value)
Method 3: Filter from get_values() (no extra query needed)
Since you already have access to child_product.attr.get_values(), you can filter that QuerySet directly to get the value you want:
# Iterate through the existing attribute values to find Brand brand_value = next( (attr_val for attr_val in child_product.attr.get_values() if attr_val.attribute.name == "Brand"), None # Return None if no match is found ) if brand_value: print(brand_value.value) # Outputs "Britania"
This last method avoids making an extra database query, which can be helpful if you're already fetching the values elsewhere.
内容的提问来源于stack exchange,提问作者Chirag Kalal

