不知道在运行时更新哪个字段

时间:2010-06-10 10:56:16

标签: django-models

有没有更好的方法来做这样的事情:

if status == 1:
    mymodel.drafted_date = date.today()
if status == 2
    mymodel.registered_date = date.today()
if status == 3
    mymodel.reported_date = date.today()
if status == 4
    mymodel.checked_date = date.today()
if status == 5
    mymodel.end_date = date.today()

我认为可能有类似的东西:

field_to_update = get_the_field_from_a_list_somewhere()
mymodel[field_to_update] = date.today()

(对不起......我有点像菜鸟)

1 个答案:

答案 0 :(得分:1)

statusmap = {1: 'drafted_date', 2: 'registered_date', ...}

  ....

setattr(mymodel, statusmap[status], date.today())