Django model field by variable

前端 未结 1 434
旧时难觅i
旧时难觅i 2021-02-01 03:44

Quick question. I\'m trying yo access one of the fields of a model using a variable.

class ExampleModel(models.Model):
      the_field = models.CharField()
              


        
1条回答
  •  一向
    一向 (楼主)
    2021-02-01 04:30

    You can use pythons getattr function to do this. Pass the field name in as the attribute.

    getattr(model, fieldtoget)
    

    Since fieldtoget is a variable, this is dynamic.

    You can use setattr to set it the same way.

    0 讨论(0)
提交回复
热议问题