def get_queryset(self, request): qs = super().get_queryset(request) result = [] if 'name' in request.GET and request.GET['name'] != 'none': # 条件查询 qs = warehousePeople.objects.filter(name=request.GET['name']) if 'subjectMatter' in self.list_display: self.list_display.remove('subjectMatter') if 'apply_prove' not in self.list_display: self.list_display.append('apply_prove') qs = qs.values('month', 'warehouse').annotate(apply_prove=Count('id')).distinct() for item in qs: warehouse = warehouseInformation.objects.get(id=item['warehouse']) obj = warehousePeople(month=item['month'], warehouse=warehouse) obj.apply_prove = item['apply_prove'] result.append(obj) 怎么将result转换为QuerySet,并且保留result列表中自定义字段apply_prove 代码应该怎么修改
时间: 2023-12-09 19:04:57 浏览: 97
要将`result`转换为`QuerySet`并保留自定义字段`apply_prove`,可以使用`QuerySet`的`values()`和`annotate()`方法来实现。下面是修改后的代码:
```python
from django.db.models import Count
def get_queryset(self, request):
qs = super().get_queryset(request)
result = []
if 'name' in request.GET and request.GET['name'] != 'none':
# 条件查询
qs = warehousePeople.objects.filter(name=request.GET['name'])
if 'subjectMatter' in self.list_display:
self.list_display.remove('subjectMatter')
if 'apply_prove' not in self.list_display:
self.list_display.append('apply_prove')
qs = qs.values('month', 'warehouse').annotate(apply_prove=Count('id')).distinct()
for item in qs:
warehouse = warehouseInformation.objects.get(id=item['warehouse'])
obj = warehousePeople(month=item['month'], warehouse=warehouse)
obj.apply_prove = item['apply_prove']
result.append(obj)
# 将result转换为QuerySet并保留自定义字段apply_prove
qs = warehousePeople.objects.none()
for obj in result:
qs |= warehousePeople.objects.filter(month=obj.month, warehouse=obj.warehouse).values(*self.list_display).annotate(apply_prove=obj.apply_prove)
return qs
```
这里使用了`qs.values('month', 'warehouse').annotate(apply_prove=Count('id')).distinct()`来计算每个月、每个仓库的`apply_prove`值,并将结果存储在`item['apply_prove']`中。然后,将每个`item`转换为`warehousePeople`对象,并将`apply_prove`值存储在`obj.apply_prove`中。最后,使用`|=`操作符将每个`obj`对应的`QuerySet`合并到`qs`中,并返回`qs`。
阅读全文