我正在尝试创建一个动态函数,该函数动态添加属性以轻松地在 jinja 模板中访问值。
此代码正在运行,但它是静态的。
# Used to display a cart summary of items that have been pledged.
products_in_cart = Cart.query.filter(Cart.campaign_id == campaign_id).all()
# total_cart_quantity(products_in_cart, "quantity", "quantity_total")
for item in products_in_cart:
item.quantity_total = 0 #Adding the attribute quantity_total
for item_loop2 in products_in_cart:
if item.user_id == item_loop2.user_id:
item.quantity_total = item.quantity_total + item_loop2.quantity
# Remove duplicate objects based on user_id attribute.
new_set = set()
new_list = []
for obj in products_in_cart:
if obj.user_id not in new_set:
new_list.append(obj)
new_set.add(obj.user_id)
products_in_cart = new_list
Run Code Online (Sandbox Code Playgroud)
我想根据传递给函数的参数使添加的属性名称动态化,以便我可以在其他地方使用。点表示法不起作用,因为我需要一个变量来命名属性。obj[variable_atrbute] 错误。setattr() …