How to regroup entries in Django by model field (More complex query)?


This Content is from Stack Overflow. Question asked by Laz22434

First i’m not an exeperienced developer in Django, i use Django 4.0.6 on windows 10 and python 3.8.9 in a virtual environment.

I need help with my query in Django:

first here’s my model:

from django.db import models

class MyWords(models.Model):
    WordText=models.CharField(max_length=1000, unique=True)

and i have this sqllite database table with the following entries as example:


MyWords Table:

WordText  WordStatus  WordType
Dog       0           Animal
Cat       1           Animal
Car       4           Object
Lion      1           Animal
Computer  4           Inanimate Object
Stone     5           Inanimate Object
Child     4           Human

What i want to do is to get this info back this way:

data == [
{'WordType':'Object', 'WordStatus':4,'WordText':'Car'},
{'WordType':'Animal', 'WordStatus':[0,1,1], 'WordText':'Dog','Cat','Lion'},
{'WordType':'Inanimate Object', 'WordStatus':[4,5], 'WordText':'Computer','Stone'},
{'WordType':'Human', 'WordStatus':4, 'WordText':'Human'}

Essentially i want to regroup/categorize the entries by WordType so i can access them more easily.

Is this possible in Django ORM? If yes, how?

I first thought using something like a values_list with WordType as argument followed by a distinct and annotate, but i’m stucked.
Something like this:

data =MyWords.objects.all().values_list('WordType').distinct().annotate(WordStatus=?).annotate(WordText=?)

I don’t know if it’s correct because i don’t know what to replace the question marks with. I don’t know if i’m on the correct path. So can anyone guide me please?

N.B: I don’t want to use raw Sql queries if possible, because the rest of the project only uses Django ORM, that’s why i’m asking, else i would use simply raw Sql queries to do the work.


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?