Filtering in ListView

548 views
Skip to first unread message

Artem Bernatskyy

unread,
Nov 24, 2016, 2:35:30 PM11/24/16
to Django users
Hello,

how can i accomplish filtering in ListView via GET ?

Now i am trying it with ListView and FormMixin...

To keep long story short:
- we are visiting page and filling form (which are generating from forms.py)
- than we are sending it via GET to the same page
- and somehow we need to validate income data and to filter by it


Any help is highly appreciated.

jorr...@gmail.com

unread,
Nov 25, 2016, 3:38:42 AM11/25/16
to Django users
If you're ok with using an external package you can check out django-filter, it makes filtering very easy.

Sergiy Khohlov

unread,
Nov 25, 2016, 5:52:01 AM11/25/16
to django-users
simplest way is update  get_content_data in view: 
 Take a look at example : 


class CompanyDetail(TemplateVariables, LoggedInMixin, DetailView):
    """ """
    model = Company
    template_name = 'company/company_detail.html'

    def cars(self):

        return Car.objects.filter(Company_id=context['company'].id)

    def get_context_data(self, **kwargs):
        """ filtering cars assigned to company with last coord"""
        context = super(CompanyDetail, self).get_context_data(**kwargs)
        CarList = Car.objects.filter(Company_id=context['company'].id) 
        PointList = []
        CarListFiltered = []
        for car in CarList:
            if Points.objects.filter(Car_id = car.id).exists():
                point = Points.objects.filter(Car_id = car.id).order_by('CreatedTime').last()
                PointList.append( point)
                CarListFiltered.append(car)
        context['Cars'] = CarListFiltered
        context['PointList'] = zip(CarListFiltered, PointList)
        return context




 This view returns  some additional data  but main idea is clear (line  with Car.object.filter)



Many thanks,

Serge


+380 636150445
skype: skhohlov

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b704e15f-b422-4f31-a773-53f995946f7c%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Artem Bernatskyy

unread,
Nov 25, 2016, 1:04:56 PM11/25/16
to Django users
Wow, tried it and it is working like a charm !

Artem Bernatskyy

unread,
Nov 26, 2016, 3:25:05 PM11/26/16
to Django users
If anyone is interested how  i accomplished this without django-filter

http://pastebin.com/6NLuM3eQ
Reply all
Reply to author
Forward
0 new messages