开发者

Set model field choices attribute at run time?

开发者 https://www.devze.com 2022-12-22 05:15 出处:网络
Is there any easy way to 开发者_如何学Godo so?You can set the choices attribute to any iterable:

Is there any easy way to 开发者_如何学Godo so?


You can set the choices attribute to any iterable: http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices

I haven't tested this myself so I'm not sure when the choices attribute is actually evaluated, but you may be able to assign a generator function that would calculate your desired choices.

You might also investigate using the Model post_init signal: http://docs.djangoproject.com/en/1.1/ref/signals/#post-init

This will give you access to your model after Django has initialized it and so you could set the choices at that time. You'd probably want to go through the "_meta" interface like so:

instance._meta.get_field_by_name('FIELD_NAME')[0].choices = [<choices>...]


Set the choices in __init__().

0

精彩评论

暂无评论...
验证码 换一张
取 消