control the empty data in django filter

Viewed 37

I was coding the backend using Django. I am a beginner in Django. I used a filter to filter some post requests from the HTML form. here is the code.

@api_view(["POST"])
def program_search(request):
    Data_List = []
    MyFilter = CreateProgram.objects.filter(price__lte=request.POST['price'], 
    days=request.POST['days']).values() 
    ...

but if I send a request from HTML form that one field of data be null the filter function cant handle it.

1 Answers

I hope you can make use of a simple if... clause to handle the situation

@api_view(["POST"])
def program_search(request):
    price = request.POST.get('price')
    days = request.POST.get("days")
    if price and days:
        qs = CreateProgram.objects.filter(price__lte=price, days=days)
    else:
        # in case of empty filter params from HTML, return empty QuerySet
        qs = CreateProgram.objects.none()

    # `qs` variable holds your result
Related