django 序列化程序字段上的逻辑

2cmtqfgy  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(185)

我正在尝试研究如何运行一些逻辑来从我的序列化程序(或其他地方)中获取某些对象。
我有以下几点:

class Parent(models.Model):
    name = models.CharField(max_length=255)

class Child(models.Model):
    name = models.CharField(max_length=255)
    parent = models.ForeignKey(
        Parent, related_name='children', on_delete=models.CASCADE)

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Child
        fields = (
            'id',
            'name',
        )

class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer()

    class Meta:
        model = Parent
        fields = (
            'id',
            'name',
            'children',
        )

class ParentViewSet(viewsets.ModelViewSet):
    serializer_class = ParentSerializer
    queryset = Parent.objects.all()

class ChildViewSet(viewsets.ModelViewSet):
    serializer_class = ChildSerializer
    queryset = Child.objects.all()

我想在parent响应中添加一个字段:first_child,它是name的第一个子字段(实际上,这个逻辑会稍微复杂一些,例如,多个字段之和的最大值)。我还将删除children字段,以支持first_child字段,因为这些字段的数量太多,无法像这样内联显示。

1bqhqjot

1bqhqjot1#

可以使用to_representation方法

class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer()

    def to_representation(self, instance):
        data = super().to_representation(instance=instance)
        first_child = instance.children.order_by("name").first()
        data["first_child"] = ChildSerializer(first_child, read_only=True).data if first_child else None
        return data

    class Meta:
        model = Parent # change model name
        fields = (
            'id',
            'name',
            'children',
        )

或者,使用SerializerMethodField

class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer()
    first_child = serializers.SerializerMethodField()

    def get_first_child(self, instance):
        first_child = instance.children.order_by("name").first()
        if first_child:
             return ChildSerializer(first_child, read_only=True).data
        return None

    class Meta:
        model = Parent # Change model here
        fields = (
            'id',
            'name',
            'children',
            'first_child',
        )

相关问题