Luiz C.
Luiz C.

Reputation: 776

Set model field choices attribute at run time?

Is there any easy way to do so?

Upvotes: 5

Views: 3703

Answers (2)

Brian Luft
Brian Luft

Reputation: 1173

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>...]

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

Set the choices in __init__().

Upvotes: 1

Related Questions