[Fixed]-Set Django model field by choice text name

1👍

You can use this workaround:

m.type = dict((key,value) for (value,key) in MyModel.TYPE_CHOICES)['One']

0👍

You should make one property for it. So you can use whenever you want.

class MyModel(object):
     TYPE_CHOICES = ((1, "One"), (2, "Two"))
     type = models.SmallIntegerField(choices=TYPE_CHOICES)

     def getx(self):
         return self.type

     def setx(self, val):
           ch = filter(lambda y: y if y[1] == val else None, self.TYPE_CHOICES)

         self.type = ch[0][0]
     type_val = property(getx, setx)

then save like this.

m = MyModel()
m.type_val = "One"
m.save()

it will save into type.

Hopefully, it will work for you. 🙂

Leave a comment