2 years ago

#63772

test-img

Abhishek Dubey

Django queryset multiple fields seaching with startwith

Can we add startswith with multiple fields? With one field it will work fine for me but with multiple fields, it gives an error to me.

def find_user_by_name_location():
    qs = User.objects.all()
    query_name = request.POST.get('name')
    location = request.POST.get('location')


    if query_name:
        q1 = Q(*[
            Q(('first_name__istartswith', term)) | Q(('last_name__istartswith', term))
            for term in query_name.split()
        ])
        q2 = Q(*[
            Q(('first_name__icontains', term)) | Q(('last_name__icontains', term))
            for term in query_name.split()
        ])
        qs = qs.filter(q1).union(qs.filter(q2))

    if location:
        q1 = Q(town__istartswith=location)
        q2 = Q(town__icontains=location) | Q(post_code__icontains=location) | Q(post_area__icontains=location) | Q(street__icontains=location) | Q(country__icontains=location) | Q(agency__operating_areas__icontains=location)
        
        qs = qs.filter(q1).union(qs.filter(q2))

    return qs.all()

For Example: We search with both(location and name) then it will give first priority to first_name from name and town from location searching.

{
    "first_name": "Katja",
    "last_name": "Tukiainen",
    "town" : "Helsinki",
    "country": "Helsinki",
},
{
    "first_name": "Kia",
    "last_name": "Reijonen",
    "town": "Espoo",
    "country": "Helsinki",
},
{
    "first_name": "Sanna",
    "last_name": "Kiander",
    "town": "Helsinki",
    "country": "Espoo",
}

If we search with both then. it will give me a union-related error, Please suggest me better way to search with multiple fields using startswith or another way to solve this issue.

Thanks in advance.

python-3.x

django-rest-framework

django-views

union

0 Answers

Your Answer

Accepted video resources