I have the following simplified models.
class Service(models.Model):
...
class ServiceLogs(models.Model):
service = models.ForeignKey(Service, related_name='logs', ...)
who_did = models.ForeignKey(User, ...)
role_played = models.CharField(choices=(('CA','CA'),
('CO', 'CO'),
('TO', 'TO')), ...)
I know I can find out who played what role by calling
<service obj>.logs.filter(role='CA')
, but this approach hits the database 3 times per object given I have 3 roles.
I was reading the documentation about aggretation and annotation, but all the examples use numeric values like Sum, Avg, etc. I tried using Q
for lookups, but Django complains with the message 'WhereNode' object has no attribute 'output_field'
Can I make this query more efficient so I hit the database once per object?