DRF外键序列化过滤

编程

背景:

  • 商户对应的材料,无效之后还会在前端显示。

参考

serailzers.py

  • 过滤有效的数据

class FilterValidListSerializer(serializers.ListSerializer):

def to_representation(self, data):

logger.info("data:{}".format(type(data)))

data = data.filter(status=SystemStatus.VALID)

return super(FilterValidListSerializer, self).to_representation(data)

主表:商户(1)

子表: 材料(N)

class MaterialBasicSerializer(MaterialOnlyCategoryTypeSerializer):

status = serializers.SerializerMethodField(help_text=u"使用状态")

extra = serializers.SerializerMethodField(help_text=u"extra")

@staticmethod

def get_extra(obj):

if obj.extra:

return fmt_extra(obj.extra)

else:

return None

@staticmethod

def get_status(obj):

status = SystemStatus.CHOICES_MAP.get(obj.status)

return status

class Meta:

model = Material

fields = ["id", "x", "status"]

list_serializer_class = FilterValidListSerializer # 加入数据过滤

class SpotDetailSerializer(SpotSerializer):

def to_representation(self, instance):

user = self.context.get("request").user

ret = super(SpotDetailSerializer, self).to_representation(instance)

return ret

# 子表嵌套序列化.spot.materials

materials = MaterialBasicSerializer(

many=True

)

class Meta:

model = Spot

fields = ["id", "xxx", "materials"]

以上是 DRF外键序列化过滤 的全部内容, 来源链接: utcz.com/z/511297.html

回到顶部