Ewanw
Ewanw

Reputation: 738

Pivot query set by variable in Django

I get a result set of objects in a given relationship. I would like to regroup them by another parameter. Is there an easy way to do this? I fe

Structure:

class Domain(models.Model):
    name = models.CharField(max_length=250)

class MetaObject(models.Model):
    name = models.CharField(max_length=250)
    object_type = models.ForeignKey('Type')
    domain = models.ForeignKey('Domain', models.DO_NOTHING, blank=True, null=True)

class Type(models.Model):
    name = models.CharField(max_length=250)

Pseudocode sample:

for dom in Domain.objects.all():
    for mo in dom.metaobject_set.all():
       print mo + ' ' + mo.object_type

What I would like is to pivot my data so instead of getting

Domain 1
  object 1, type 1
  object 2, type 1
  object 3, type 2

I instead would like a result set I can work with in a template that looks like the following

Domain 1
  Type 1
    object 1
    object 2
  Type 2
    object 3

I feel like what I otherwise need to do is get all the distinct types for a set of objects in a specified domain and then iterate through those. I can't start with Types at the top as I want them to be per domain.

Upvotes: 0

Views: 516

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599796

You should be able to do this by querying for Types directly in your inner loop. Use prefetch_related to make it a bit more efficient.

for dom in Domain.objects.all():
    for tp in Type.objects.filter(metaobject__domain=dom).prefetch_related('metaobject'):
       print('Type {}'.format(tp))
       for mo in tp.metaobject_set.all():
           print(mo)

Another approach might be to grab all the metaobjects and regroup in Python by type.

Upvotes: 1

Related Questions