gpt4 book ai didi

django 查询集按字段分组

转载 作者:行者123 更新时间:2023-12-05 04:08:02 28 4
gpt4 key购买 nike

我有一个 ListView ,想根据外键 ID 进行分组

View .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

模型.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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com