[Answer]-Filter the data from database using django filter

1👍

Your form is using location ids for its value keys, not location titles. ChoiceFields use the first part of each tuple in choices as the value which gets POSTed and the second part of each tuple is just the name of the choice as the user sees it. Add a print statement to check the value of your loc_id and you’ll see what I mean.

So you’ll want to look up a location title for the location id in request.POST. If your ReportLocation model has a ForeignKey to Location you can do something like

location_list = ReportLocation.objects.filter(location__id=loc_id)

but if that doesn’t work with your schema you might have to look up the title as a separate query. Here’s a simplistic example:

def search(request):
    reportlist = []
    loc_id = request.POST.get('location')
    if loc_id:
        # This will cause an error if loc_id isn't found,
        # it's just here as an example
        loc_title = Location.objects.get(id=loc_id).title
        location_list = ReportLocation.objects.filter(title=loc_title)
        for locaton in location_list:                       
            reportlist.append(locaton.report)
👤Kevin

Leave a comment