[Fixed]-Django queryset search on multiple models, return the same object

1👍

Try this:

key = {}
year = form.cleaned_data["year"]
residence = form.cleaned_data["residence"]
starred = form.cleaned_data["starred"]
education_type = form.cleaned_data["education_type"]

if year:
    key['birthdate__year'] = year

if residence:
    key['residence__icontains'] = residence

if starred:
    key['starred'] = starred

if education_type:
    e = Education_type.objects.filter(title=education_type)
    result_education = Education.objects.filter(education_type=e).values_list('profile_id', flat=True)
    key['id__in'] = result_education

result_profile = Profile.objects.filter(**key).order_by('first_name')

0👍

My solution working on more than 2 models, based on @Geo Jacob solution, thank you

I make a check and put in key['id__in'] only matched id from the previous query, so as to intersect the results

            key = {}
            statokey = 0

            year = form.cleaned_data["year"]
            residence = form.cleaned_data["residence"]
            starred = form.cleaned_data["starred"]
            education_type = form.cleaned_data["education_type"]
            valutation = form.cleaned_data["valutation"]

            if year:
                key['birthdate__year'] = year

            if residence:
                key['residence__icontains'] = residence

            if starred:
                key['starred'] = starred

            if education_type:
                e = Education_type.objects.filter(title=education_type)
                result_education = Education.objects.filter(education_type=e).values_list('profile_id', flat=True)
                if statokey > 0:
                    for r in result_education:
                        for k in key['id__in']:
                            if r == k:
                                key['id__in'] = str(r)

                else:
                    key['id__in'] = result_education
                    statokey += 1

            if valutation:
                result_valutation = Status.objects.filter(valutation=valutation).values_list('profile_id', flat=True)
                if statokey > 0:
                    for r in result_valutation:
                        for k in key['id__in']:
                            if r == k:
                                key['id__in'] = str(r)
                else:
                    key['id__in'] = result_valutation
                    statokey += 1


            result_profile = Profile.objects.filter(**key).order_by('first_name')
👤Skar3

Leave a comment