Consider the following example model:
class MyModel(models.Model):
TYPE_ONE = 1
TYPE_TWO = 2
TYPE_CHOICES = (
(TYPE_ONE, "One"),
(TYPE_TWO, "Two"),
)
type = models.SmallIntegerField(choices=TYPE_CHOICES)
# ... other fields
This works well internally, as I now have a 'constant' which I can reuse throughout my code to refer to each type
.
However, when this model gets serialized and sent to the client as JSON through a custom API Controller implementation, it turns the type into it's textual representation. It might look like this:
{
'id': 1,
'type': 'One'
}
This is fine, however I'd like to be able to set the field value based on this text version (the consumer of my API wants to be able to pass friendly strings, not ints).
When constructing a model instance, how can I set type
to One
, and have it automatically convert it into the relevant int
?
Something like:
m = MyModel()
m.type = "One"
m.save() # throws a ValueError
Thanks
您可以使用以下解决方法:
m.type = dict((key,value) for (value,key) in MyModel.TYPE_CHOICES)['One']
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. :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.