Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django queryset group by field

i have a listview and want to group by based on foreign key 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)       

Question: I would like to group by the queryset by ItemType_id in the MyModel

Expectation: select * from MyModel group by ItemType_id

like image 310
user2851703 Avatar asked Oct 22 '25 16:10

user2851703


1 Answers

You must doing something like this:

from django.db.models import Count

MyModel.objects.values('Type').annotate(dcount=Count('Type'))

MyModel.objects.values('Type__id').annotate(dcount=Count('Type__id'))

you can also read this document can help you.... good luck!

like image 113
Mbambadev Avatar answered Oct 25 '25 16:10

Mbambadev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!