1

I have a following model.

class Compared(models.Model):
    store = models.ForeignKey(Store)
    product = models.ForeignKey(Product)

    class Meta():
        unique_together = ('store', 'product')

And with following type of data in it.

(store, product)
(1, 1)
(2, 1)
(3, 1)
(2, 2)
(2, 3)
(3, 3)
(3, 2)

I want to group by product and get all stores in that group.

(product, (stores))
(1, (1, 2, 3))
(2, (2, 3))
(3, (2, 3))

Is there a built in query function to achieve that or I have to manually make them so?

Umair A.
  • 6,690
  • 20
  • 83
  • 130
  • Maybe [that](http://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django) helps you. – Leandro Jun 18 '13 at 19:05
  • Hope you tried searching first Umair. Does this answer your question: [How to query as GROUP BY in django?](http://stackoverflow.com/a/629691/977931)? – stellarchariot Jun 19 '13 at 01:36

1 Answers1

0

You can group with itertools:

from itertools import group_by    
cs = Compared.objects.all().order_by( 'product__pk' ) )
for p, l in groupby( l , key = lambda x: x.store.pk ):
    print p.pk                 #the produt name
    print [ s.pk for s in l ]  #stores pks
    print ( p.pk, tuple( s.pk for s in l  ) )

Notice: syntax not tested.

Notice: this grouped 'in memory' but in database.

Notice: order by is important.

dani herrera
  • 48,760
  • 8
  • 117
  • 177