Append choices to choice list in Django models dynamically

Ashish Gupta Source

I want to select the options from a list in my django models. But the options in the list are populated in the post_save() method.The situation is like this:

  • I enter some attributes in the table1 based on which the value of other attributes of the table is calculated using different algorithms in post_save() method.

  • Now I want these values from different algorithms to be shown as choices to the attribute(which were set to blank intially or some default value) of table1 after saving it for the first time.

  • There are constraints only distinct values should as choices and the choice list should contain only those values which are calculated using the attributes of this tuple/row of the table.

  • I tried to use choice option and appending the values from diff algos to the list but that creates two problems:

    • If I save two entries then the list contains the values that are calculated using the attributes of both the entries(filtering required)

    • If I save a entry twice then the duplicate entries are appended to the list.

Also foreign key may be a option but how to filter foreign key according the tuples which generated it.

I tried to explain the problem and I feel code is not required. Comment if any details required in regard to question.

pythonmysqldjango

Answers

answered 4 years ago kpacn #1

I think your choice of type field is incorrect. Basically CharField with choices has limited functionality and you can't do this with it you can only filter the choices you declared initially but you can't add new ones on the fly (you will see them but they will not pass the field validation). I think you should go with ForeignKey where you do not have such limitations. You can build it dynamically without ptoblems. I can't tell you the queries without seeing some code.

comments powered by Disqus