Ticket #2445: choices_func.diff

File choices_func.diff, 2.1 KB (added by Dmitri Fedortchenko <zeraien@…>, 17 years ago)

This patch is still a bit unpredictable with edit_inline objects, but works with normal relationships.

  • django/db/models/base.py

     
    163163                val = field.get_default()
    164164            setattr(self, field.attname, val)
    165165
     166        for item in dir(self):
     167            if item.startswith('choices_for__'):
     168                choice_func = getattr(self,item)
     169                if callable(choice_func):
     170                    field_name = choice_func.__name__[len('choices_for__'):]
     171                    self._meta.get_field(field_name)._choices = choice_func
     172       
    166173        if kwargs:
    167174            for prop in kwargs.keys():
    168175                try:
  • django/db/models/fields/__init__.py

     
    88
    99from django.db import get_creation_module
    1010from django.db.models import signals
     11import django.db.models.query
    1112from django.dispatch import dispatcher
    1213from django.conf import settings
    1314from django.core import validators
     
    340341        "Returns a list of tuples used as SelectField choices for this field."
    341342        first_choice = include_blank and blank_choice or []
    342343        if self.choices:
    343             return first_choice + list(self.choices)
     344            if callable(self.choices):
     345                choices = self.choices()
     346            else:
     347                choices = self.choices
     348            print "self",dir(self)
     349            # If choices is a QuerySet, convert into a tuple list ((pk,__unicode__),etc)
     350            if isinstance(choices, django.db.models.query.QuerySet):
     351                choices = [(x._get_pk_val(), smart_unicode(x)) for x in choices]
     352           
     353            return first_choice + list(choices)
     354           
    344355        rel_model = self.rel.to
    345356        if hasattr(self.rel, 'get_related_field'):
    346357            lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)]
Back to Top