2

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

1 Answer 1

1

Well, since foreign key is actually id of object it's refferring to, you have to run a query to get this id. But if you already have id of parent object you can create a child object w/o fully loading parent:

C.objects.update_or_create(
    a_id=id_of_a, 
    b_id=id_of_b,
    c_param_1='value'
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.