我有一个具有flags
属性的模型,它是多个值的位掩码。我想使用django-rest-framework
将其公开为API,其中不同的标志是不同的布尔属性。如果标志为FLAG_NEW=1
,FLAG_DELETED=2
,我想公开isNew
和isDeleted
字段。对于只读模型,这很简单 - 只需使用SerializerModelField
并获取是否设置了标志。但是,当我想要反序列化时,这不起作用(这是一个只读字段)。我可以使用自定义字段,但是我应该在source=
参数中添加什么?如果我放source=flags
,他们会互相覆盖,如果我不知道,那我怎么得到初始值?
class MyModel(models.Model):
FLAG_NEW = 1
FLAG_DELETED = 2
flags = models.IntegerField()
....
class MyModelSerializer(models.Model):
isDeleted = ???
isNew = ???
答案 0 :(得分:2)
class MyModel(models.Model):
FLAG_NEW = 1
FLAG_DELETED = 2
flags = models.IntegerField(default=0)
@property
def isNew(self):
return self.flags | self.FLAG_NEW
@isNew.setter
def isNew(self, value):
if value:
self.flags |= self.FLAG_NEW
else:
self.flags &= ~self.FLAG_NEW
@property
def isDeleted(self):
return self.flags | self.FLAG_DELETED
@isDeleted.setter
def isDeleted(self, value):
if value:
self.flags |= self.FLAG_DELETED
else:
self.flags &= ~self.FLAG_DELETED
...
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'isNew', 'isDeleted', ...)