choices being a QuerySet or callable

234 views
Skip to first unread message

Brian Rosner

unread,
Jul 23, 2007, 6:28:19 PM7/23/07
to django-d...@googlegroups.com
I have recently come across needing to have the choices of a
django.db.models.Field be dynamic or atleast a callable. I asked in
the IRC room, but it turns out choices only accepts a iterable. While
an QuerySet is an iterable, it would end up caching the value of the
returned values. I don't know if a QuerySet will even work. In my
situation I am attempting to pass in a call to a function, but the
returned value is then cached and won't be reloaded until the model or
the server is reloaded.

I have found this ticket in Trac:

http://code.djangoproject.com/ticket/1891

I was wondering what everyone's stance is on inclusion of something like this.

--
Brian Rosner
http://www.brosner.com/blog


oggie rob

unread,
Jul 23, 2007, 6:54:26 PM7/23/07
to Django developers
> I was wondering what everyone's stance is on inclusion of something like this.

It is not really needed, you can override the field. Take a look at
the __init__ call in http://www.djangosnippets.org/snippets/26/ and
you can do that with a model field as well as a form field. Yes it is
a bit of a pain but you won't need to do it very often, especially
since you can use the field again and again (i.e. in different
models).

Apart from not needing it, a fairly weak reason against including it
is that if your query gets large, it becomes unusable (i.e. choices
gets too long). Also you might not want to use __unicode__ or __str__
in the choices field but something shorter or more specific to the
model that is referencing it. To me it seems more sensible to create a
single custom field which you can change in just one place.

BTW, it probably would be better to post first in DJ Users. People
have worked through problems like this already and have some pretty
neat solutions or ideas to some interesting problems.

-rob

Reply all
Reply to author
Forward
0 new messages