Wednesday 21 August 2013

how to use __in with __startswith in django queryset

Hi All,

Today we will see the code which will help us to use __in  with __startswith or any other filter.

First we will learn use of __in .

__in   ----> it is used to filter data from a list

namelist = ['sachin', 'dravid', 'dhoni', 'khan']
Player.objects.filter(name__in=namelist)                                                                          

Use of __startswith or __endswith to filter data based on starting ,ending pattern in any string .
Player.objects.filter(name__startswith='sac')

if you want to filter query where name will start with words given in any list you will use.


from django.db.models import Q
def startwithin(namelist):
        q = Q()
        for names in namelist:
            q |= Q(name__startswith=names)    # | will union all objects 
        return Player.objects.filter(q)
     


Thanks
Prashant Gaur

No comments:

Post a Comment