In the current project that i'm working on, i need to regroup (group) a queryset by category and put contents with same category in a list all provided together.
I have the following model structure:
class Category(models.Model):
title = models.CharField(max_length=255)
class Item(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey(to="Category", verbose_name=_('category'), related_name='items',
on_delete=models.SET_NULL, null=True, blank=True)
I would like the output serialized result to be like:
{
"category_title_1":[
{
"id": 1,
"title" : "something",
},
{
"id": 2,
"title": "something else",
}
],
"category_title_2": [
{
"id": 3,
"title": "another string",
},
{
"id": 4,
"title": "and yet another title",
}
]
}
I know i can always iterate over the queryset and group them manually, i'm wondering if there is a native efficient way to do this.
Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…