user2439275
user2439275

Reputation: 79

filter the data from database using django filter

views.py

def search(request):
    reportlist = []
    loc_id = request.POST.get('location')
    if loc_id:
        location_list = ReportLocation.objects.filter(title=loc_id)
        for locaton in location_list:                       
            reportlist.append(locaton.report)

forms.py

class SearchFilterForm(Form):
    location = forms.ChoiceField(widget=forms.Select(), choices='',required=False, initial='Your name')

    def __init__(self,user_id, *args, **kwargs):
        super(SearchFilterForm, self).__init__(*args, **kwargs)
        self.fields['location'] = forms.ChoiceField(choices=[('','All Location types')]+[(loc.id, str(loc.title)) for loc in Location.objects.filter(user=user_id).exclude(parent_location_id=None)])

models.py

class ReportLocation(models.Model):   
    report = models.ForeignKey(Report)    
    title = models.CharField('Location', max_length=200)

How to filter the title field in ReportLocation field with the selected choice.I tried with above filter query in views.py,but it is not showing any filtered data.Need help

Upvotes: 0

Views: 4818

Answers (1)

Kevin
Kevin

Reputation: 959

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)

Upvotes: 1

Related Questions