0

Scenario: Form that give values to filter some records. I have 4 models A, B, C and D.

A Have OneToOne relationship with B

B Have ManyToOne relationship with C

C Have ManyToOne relationship with D

Form value given is a field in model D, and the record that I'll retrieve is in model A

I've Tried:

records= A.objects.filter(
            a_field = "form_given_value_1",
            B__b_field = C.objects.filter( 
                c_field = D.objects.filter(
                    d_field=form_given_value_2
                )
            )
        )

I got that error:

SyntaxError: keyword argument repeated

then after some search I tried given answer here:

records = A.objects.filter(
             a_field = "form_given_value_1",
             B__b_field__c_field__d_field = form_given_value_2
          )

It doesn't give me errors but it doesn't give records also!..

how to achieve that approach ?

0

1 Answer 1

0

First you need to check if form_given_value_* is null because if any is equal to null (no input) the filter() will return nothing

Second after check you need to pass filters to filter() upon your check

We achieve that like below:

    from django.db.models import Q

    filters = Q()
    if form_given_value_1:
        filters &= Q(a_field = "form_given_value_1",)
    if form_given_value_2:
        filters &= Q(B__b_field__c_field__d_field = form_given_value_2,)

    records = A.objects.filter(filters)
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.