python - django - how to do this with kwargs -


i wondering when touch db when doing queries. more precisely, when query performed:

i have kwargs dic:

kwargs = {'name__startswith':'somename','color__iexact':'somecolor'} 

but name__startswith query, need distinct(). , not color__iexact.

i thought, set name__startswith distinct() in loop this:

for q in kwargs:    if q == 'name__startswith':     thing.objects.filter(name__startswith=somename).distinct('id') 

and query dynamically:

allthings = thing.objects.filter(**kwargs) 

but somehow wrong, seem doing 2 different things here..

how can these 2 queries dynamically?

django querysets lazy, actual queries aren't evaluated until use data.

allthings = thing.objects.filter(**kwargs)  if 'name__startswith' in kwargs:   allthings = allthings.distinct('id')    

no queries should preformed above unitl use data. great filtering queries wish do


from docs:

querysets lazy – act of creating queryset doesn’t involve database activity. can stack filters day long, , django won’t run query until queryset evaluated. take @ example:

>>> q = entry.objects.filter(headline__startswith="what") >>> q = q.filter(pub_date__lte=datetime.date.today()) >>> q = q.exclude(body_text__icontains="food") >>> print(q) 

though looks 3 database hits, in fact hits database once, @ last line (print(q)). in general, results of queryset aren’t fetched database until “ask” them. when do, queryset evaluated accessing database. more details on when evaluation takes place, see when querysets evaluated.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -