我有一个 ListView ,想根据外键 ID 进行分组
View .pyclass SelectListView(ListView):
model=MyModel
template_name = "/select_list.html"
context_object_name = 'selectlist'
queryset = MyModel.objects.all().values('ItemType_id')
paginate_by = 10
def get_context_data(self, **kwargs):
context = super(SelectListView, self).get_context_data(**kwargs)
context['range'] = range(context["paginator"].num_pages)
return context
模型.py
class ItemType(models.Model):
ItemType=models.CharField(unique=True,max_length=40)
class MyModel(models.Model):
Type=models.ForeignKey(ItemType)
ItemName=models.CharField(unique=True,max_length=40)
问题:我想在 MyModel 中按 ItemType_id 的查询集进行分组
期望:根据 ItemType_id 从 MyModel 组中选择 *
最佳答案
你必须做这样的事情:
from django.db.models import Count
MyModel.objects.values('Type').annotate(dcount=Count('Type'))
MyModel.objects.values('Type__id').annotate(dcount=Count('Type__id'))
您还可以阅读 this document can help you.... 祝你好运!
关于django 查询集按字段分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48135831/