django queryset按字段分组

时间:2018-01-07 09:18:12

标签: django django-models django-templates django-views

我有一个列表视图,并希望根据外键ID

进行分组  views.py
class 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
 models.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组中选择*

1 个答案:

答案 0 :(得分:0)

你必须做这样的事情:

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.... 祝你好运!