Creating a dynamic choice field django choices 动态 lazy
a. 第一种方法(admin保存出错)
I'm having some trouble trying to understand how to create a dynamic choice field in django. I have a model set up something like:
class rider(models.Model):
user = models.ForeignKey(User)
waypoint = models.ManyToManyField(Waypoint)
class Waypoint(models.Model):
lat = models.FloatField()
lng = models.FloatField()
What I'm trying to do is create a choice Field whos values are the waypoints associated with that rider (which would be the person logged in).
Currently I'm overriding init in my forms like so:
class waypointForm(forms.Form):
def __init__(self, *args, **kwargs):
super(joinTripForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.all()])
a. 第二种方法(妥妥的)
I use lazy for lazy load:
from django.utils.functional import lazy
def help_SHOP_CHOICES():
SHOP1_CHOICES = (
('Food Court', 'Food Court'),
('KFC', 'KFC'),
]
SHOP3_CHOICES = [
('Bowling Arena', 'Bowling Arena'),
('Cinemax', 'Cinemax'),
]
return choice( SHOP1_CHOICES, SHOP3_CHOICES ) #choice one
class Feed(models.Model):
...
location=models.CharField(max_length=25, choices=SHOP1_CHOICES)
def __init__(self, *args, **kwargs):
super(Feed, self).__init__(*args, **kwargs)
self._meta.get_field_by_name('location')[0]._choices = \
lazy(help_SHOP_CHOICES,list)()
测试通过
c.最简单的方法(妥妥的)
from django.utils.functional import lazy
def help_SHOP_CHOICES():
SHOP1_CHOICES = (
('Food Court', 'Food Court'),
('KFC', 'KFC'),
)
SHOP3_CHOICES = (
('Bowling Arena', 'Bowling Arena'),
('Cinemax', 'Cinemax'),
)
return choice( SHOP1_CHOICES, SHOP3_CHOICES ) #choice one
class Feed(models.Model):
...
location=models.CharField(max_length=25, choices=lazy(help_SHOP_CHOICES,tuple)()) #这里类型一定要对,list和tuple要分清楚
注意,如果help_shop_choices是从数据库里取的话,一定要加try,否则初始化django会读不到表
def help_SHOP_CHOICES():
try:
choices = get_db() #从数据库里取
except Exception, e:
return ((None,None),)
end