I'm interested in finding out whether it's possible to replace
title__contains in the above example with a variable. Why do I want to
do this? Well, here's some pseudocode:
posts = Post.objects.all()
if title checkbox is checked:
posts = posts.filter(title__contains='django')
if subheading checkbox is checked:
posts = posts.filter(subheading__contains='django')
if body checkbox is checked:
posts = posts.filter(body__contains='django')
I would love to be able to do this with a loop:
posts = Post.objects.all()
for field in ['title', 'subheading', 'body']:
posts = posts.filter(field__contains='django')
Clearly the above will not work, but is there a way to achieve the
result I'm after?
def foo(x,y,z):
print "x=" + x
print "y=" + y
print "z=" + z
d = { 'x' : 1, 'y': 2, 'z' : 3 }
foo( **d ) # same as foo( x=1, y=2, z=3 )
it's a python thing, not django necessarily
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>
>
On Feb 5, 12:23 am, Itay Donenhirsch <i...@bazoo.org> wrote:
> i guess you can do it with a dictionary, i'll give you a general example:
>
> def foo(x,y,z):
> print "x=" + x
> print "y=" + y
> print "z=" + z
>
> d = { 'x' : 1, 'y': 2, 'z' : 3 }
> foo( **d ) # same as foo( x=1, y=2, z=3 )
>
> it's a python thing, not django necessarily
>
> On Thu, Feb 4, 2010 at 1:20 PM, davidchambers
>
Thanks for the suggestion. Unless I'm mistaken, though, using a
dictionary does not solve the problem which is that .filter() seems to
require field names to be hard-coded. Django is incredibly well
designed, though, and continually surprises me, so I'm almost
_expecting_ to be pleasantly surprised here.
I discovered a post which gives an example of Itay's suggestion in
action: http://yuji.wordpress.com/2009/09/12/django-python-dynamically-create-queries-from-a-string-and-the-or-operator/.
I also found this section of Python's documentation useful:
http://docs.python.org/tutorial/controlflow.html#keyword-arguments.
Thanks for your replies. Sorry for being slow on the uptake. I am
relatively new to Python and didn't realize that it's possible to pass
a dictionary to a function in place of arguments. Cool!
On Feb 5, 2:25 am, Itay Donenhirsch <i...@bazoo.org> wrote:
> i don't see any way for a python function to _require_ a parameter to
> be hardcoded.
> i would be VERY surprised otherwise. this must work...
> i agree about python being designed awesomely though! :)
>
> On Thu, Feb 4, 2010 at 3:13 PM, davidchambers
>