我正在尝试向查询集中的每个对象添加两个属性,并向特定子集添加一个:
causelist_data = CauseHierarchy.objects.filter(cause_set_version_id=cause_set_version_id
).extra(order_by=['sort_order']
).prefetch_related('cause_id','parent_id')
for c in causelist_data:
# adding this attribute works
c.display_name = c.cause_id.cause_name + " (" + c.cause_id.acause + ")"
if len(c.path_to_top_parent.split(',')) == 1:
# adding this attribute works as well
c.immediate_parent = c.path_to_top_parent.split(',')[-1]
else:
c.immediate_parent = c.path_to_top_parent.split(',')[-2]
# this is the problem
parent = causelist_data.filter(cause_id=c.immediate_parent)[0]
parent.is_parent = True
当我为每个对象添加显示名称以及基于条件添加immediate_parent属性时,修改起作用。当我尝试将is_parent属性设置为已被识别为子节点的对象时,会出现问题,方法是在迭代中每个对象标识其父对象时拉动它们的id。
在shell中我尝试在循环中打印parent
对象并且它具有is_parent属性,但是当我查看循环外的causelist_data时,它同时具有display_name和immediate_parent属性。我还尝试在过滤器(parent = causelist_data.filter(cause_id=c.immediate_parent).update(is_parent=True)
)之后更新父对象,但看起来我不能添加这样的属性,只更新。
我在这里遗漏了什么吗?我的查找不正确吗?
答案 0 :(得分:0)
我认为在所有情况下你都会发出另一个查询
更好地抓住filters
你应该没问题。
filters = {cause_set_version_id:cause_set_version_id}
causelist_data = CauseHierarchy.objects.filter(filters**
).extra(order_by=['sort_order']
).prefetch_related('cause_id','parent_id')
for c in causelist_data:
# adding this attribute works
c.display_name = c.cause_id.cause_name + " (" + c.cause_id.acause + ")"
if len(c.path_to_top_parent.split(',')) == 1:
# adding this attribute works as well
c.immediate_parent = c.path_to_top_parent.split(',')[-1]
else:
c.immediate_parent = c.path_to_top_parent.split(',')[-2]
filters['cause_id'] = c.immediate_parent
parent = CauseHierarchy.objects.filter(filters**)[0]
parent.is_parent = True