首页 > 解决方案 > *** 类型错误:get_value_by_attribute() 缺少 1 个必需的位置参数:“属性”

问题描述

我正在使用 Django oscar 并尝试使用 product.attr.get_value_by_attribute() 获取产品属性键和值。而且我遇到了错误,我试图传递属性,但它仍然给我一个错误。

我的测试调试器代码如下:

(Pdb) child_product
<Product: Good Day 100 gm>
(Pdb) child_product.__dict__
{'_state': <django.db.models.base.ModelState object at 0x7fa088e1c438>, 'id': 13, 'structure': 'child', 'upc': '', 'parent_id': 12, 'title': 'Good Day 100 gm', 'slug': 'good-day-100-gm', 'description': '', 'product_class_id': None, 'rating': None, 'date_created': datetime.datetime(2019, 6, 22, 15, 30, 24, 273252, tzinfo=<UTC>), 'date_updated': datetime.datetime(2019, 6, 22, 15, 30, 24, 273270, tzinfo=<UTC>), 'is_discountable': True, 'attr': <oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470>}
(Pdb) child_product.attr
<oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470>
(Pdb) child_product.attr.__dict__
{'product': <Product: Good Day 100 gm>, 'initialised': False}
(Pdb) child_product.attr.__dict__
{'product': <Product: Good Day 100 gm>, 'initialised': False}
(Pdb) child_product.attr.get_values()
<QuerySet [<ProductAttributeValue: Brand: Britania>, <ProductAttributeValue: Variant Name: 100 gm x 12>]>
(Pdb) child_product.attr.get_all_attributes()
<QuerySet [<ProductAttribute: Brand>, <ProductAttribute: GST Rate>, <ProductAttribute: HSN Code>, <ProductAttribute: Liquid Content>, <ProductAttribute: Parent Company>, <ProductAttribute: Promo SKU>, <ProductAttribute: Selling Lot Size>, <ProductAttribute: Sub Brand>, <ProductAttribute: Tags>, <ProductAttribute: Variant Name>, <ProductAttribute: Weight>, <ProductAttribute: Weight Unit>]>
(Pdb) child_product.attr.get_value_by_attribute()
*** TypeError: get_value_by_attribute() missing 1 required positional argument: 'attribute'
(Pdb) child_product.attr.get_value_by_attribute(attribute="Brand")
*** ValueError: invalid literal for int() with base 10: 'Brand'

所以在这里我能够获得价值和所有属性,但我不知道如何通过我需要的属性获得价值。

child_product.attr.get_value_by_attribute()

因此,任何人对此有任何想法,请提供帮助。肯定会感谢您的帮助。

标签: pythondjangodjango-rest-frameworkdjango-oscar

解决方案


通过属性获取值时,必须在get_value_by_attribute方法中传递属性的实例。例如

brand = child_product.attr.get_all_attributes().first()
child_product.attr.get_value_by_attribute(attribute=brand)

您还可以通过在get_values方法的结果上调用其名称来按属性检索值。例如get

child_product.attr.get_values().get(attribute__name='Brand')

推荐阅读