python - Chaining Filters together -



python - Chaining Filters together -

given following:

instances = catalog.objects.filter( q(imdb_url=imdb_url) |q(isan=isan) |q(amg_video_id=amg_video_id) )

how same in next format, chaining each together:

instances = catalog.objects.all() if imdb_url: instances = instances.filter(imdb_url = imdb_url) # or if isan: instances = instances.filter(isan = isan) # or if amg: instances = instances.filter(amg = amg) # or

the above gives me equivalent of:

instances = catalog.objects.filter(imdb_url=imdb_url).filter(isan=isan).filter(amg=amg)

how eqivalent of q in first query?

you can create empty q object , or others accordingly using |=:

q = q() if imdb_url: q |= q(imdb_url=imdb_url) if isan: q |= q(isan=isan) if amg: q |= q(amg=amg) instances = catalog.objects.filter(q)

python django django-models django-queryset

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -