Let's suppose I have 3 models: A, B, C, with C having foreign keys relationship with both A and B. How can I avoid multiple queries, when saving a C model if I have the necessary info to retrieve A and B?
Currently my code is something like:
a = A.objects.get(title='the title', platform='the platform')
b = A.objects.get(id='the id')
C.objects.update_or_create(a=a, b=b, defaults={'c_param_1':'value'})
this sucks, since it executes at least 3 queries (4 if the C object does not exist). I would like to retrieve a and b at the db layer... how can be implemented using Django's ORM?
I currently tried to use Q objects in this way:
C.objects.update_or_create(
a=Q(a__title='the title') & Q(a__platform='the platform'),
b=Q(b__id='the id'),
c_param_1='value'
)
But I get:
TypeError: int() argument must be a string or a number, not 'Q'
ps: I'm using Django 1.7