0

I'm trying to do a query and I want to group by several fields. Some of those fields are foreign keys. When I get my query set back, I would like those foreign keys to be objects of their respective models. The only way I have found to group by a queryset is values('model1', 'model2', 'somefield'). When I do this, though, the values I get from those fields are the IDs of those objects.

What I'm looking for is an equivalent query set to this:

SELECT model1, model2, somefield, sum(something) FROM table WHERE (conditions here) GROUP BY model1, model2, somefield

And I would like model1, model2 to actually be model objects instead of just IDs.

Any good way to do this?

Thanks

Sam Creamer
  • 5,187
  • 13
  • 34
  • 49

1 Answers1

0

When you use a regular Django model query:

model_instances = Model.objects.filter(some condition).order_by('model1', 'model2', 'some_field')

model_instance gets an array of instances of class Model, and every instance's foreign key attributes are also instances of corresponding models, so model_instances[0].model1 would be an instance of 'Model1'.

You can check Django reference for making queries here.

HuLu ViCa
  • 5,077
  • 10
  • 43
  • 93
  • Yes, but that doesn't group by those models. It just orders by them. I would like to emulate `GROUP BY` in SQL. I know that I can do it with `values()` but that returns DB values instead of model instances. – Sam Creamer Nov 07 '18 at 13:10
  • Oh! In that case you can use this: https://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django – HuLu ViCa Nov 08 '18 at 14:32
  • Same problem as the one I mentioned in my previous comment. I have done some research and found that they just do not have a good way to do `GROUP BY`. Oh well! Thanks for the help. – Sam Creamer Nov 08 '18 at 15:34