Python Django-如何附加到Django查询集(值)
如何将字典附加到Django查询集中?我已经在queryset上使用了.values,但它仍然分类为queryset,当我尝试使用.append时,出现了这个错误Python Django-如何附加到Django查询集(值),python,django,Python,Django,如何将字典附加到Django查询集中?我已经在queryset上使用了.values,但它仍然分类为queryset,当我尝试使用.append时,出现了这个错误 AttributeError: 'QuerySet' object has no attribute 'append' 这是我的代码:(start和end是传入的变量,用于表示所选范围的开始月份和结束月份) 我所要做的就是将缺少的日期添加到查询集中,例如,如果我的查询集中有日期:2020年4月和2020年6月,但由于Customer
AttributeError: 'QuerySet' object has no attribute 'append'
这是我的代码:(start和end是传入的变量,用于表示所选范围的开始月份和结束月份)
我所要做的就是将缺少的日期添加到查询集中,例如,如果我的查询集中有日期:2020年4月和2020年6月,但由于CustomerInformation没有任何创建的日期在2020年5月范围内的实例,因此缺少2020年5月,因此,我希望能够插入日期为2020年5月、lead_count和client_count为0的字典,以便我的数据可视化能够正常工作
谢谢大家,谢谢大家的帮助 除非将数据添加到数据库,否则不能附加到qs。 如果需要,可以转换为列表,然后添加项目 您也可以创建一个生成器,在需要时输出附加值 比如:
def getDatat():
qs = CustomerInformation.objects.filter(salesDepartment__in=[d]).filter(created_date__range=(start,end))
qs = qs.annotate(date=TruncMonth('created_date')).values('date').annotate(lead_count=Count('status',filter=Q(status="lead"))).annotate(client_count=Count('status',filter=Q(status="client")))
qs = qs.values('date', 'client_count', 'lead_count')
this_v = None
for next_v in qs:
if this_v is None:
this_v = next_v
yield this_v
continue
# Do logic for checking if there's any needed extra values between this_v and next_V
# yield extra values
this_v = next_v
yield this_v
将其转换为列表:
list(qs)
。但是我不建议你这么做,因为查询类型的项目类型不是DICT,所以你必须以后有一个类型检查。我记得我以前看到过你的问题,所以你可以考虑:构造一个类似于列表的新类型,它是可迭代的,然后将查询结果填入其中。然后使用这个新类型,而不是直接使用queryset。@YangHG您所说的查询集的项类型是什么意思?我现在要做的是使用列表理解将其转换为列表,这样行吗?
def getDatat():
qs = CustomerInformation.objects.filter(salesDepartment__in=[d]).filter(created_date__range=(start,end))
qs = qs.annotate(date=TruncMonth('created_date')).values('date').annotate(lead_count=Count('status',filter=Q(status="lead"))).annotate(client_count=Count('status',filter=Q(status="client")))
qs = qs.values('date', 'client_count', 'lead_count')
this_v = None
for next_v in qs:
if this_v is None:
this_v = next_v
yield this_v
continue
# Do logic for checking if there's any needed extra values between this_v and next_V
# yield extra values
this_v = next_v
yield this_v