2016-11-20 101 views
1

我有一个名为Notification的模型,其名称为notification_type。现在在NotificationSerializer.__init__,我想检查模型实例的notification_type字段的值,并根据它的值,我想添加/删除序列化器上的一些字段。那可能吗?DRF - 根据实例字段值添加/排除字段

我试过self.instance里面的__init__方法,但在many=True的情况下,它是一个查询集。我想根据每个模型实例进行修改。那可能吗?

回答

1

这是可能的,但不是在串行器的__init__。请使用序列化程序的to_representation方法。

def to_representation(self, obj): 
    data = super().to_representation(obj) 
    # data is your serialized instance 

    if obj.notification_type == 'type1': 
     data.pop('attr2') 
    elif obj.notification_type == 'type2': 
     data.pop('attr1') 

    return data 
+0

谢谢。我会尝试。 – masnun