当使用Django REST框架时,序列化程序嵌套时,如何排除父级? [英] How to exclude parent when serializer is nested when using Django REST Framework?

查看:178
本文介绍了当使用Django REST框架时,序列化程序嵌套时,如何排除父级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这可能在文档中,但是我似乎无法想像出来。

I feel like this is probably in the docs but I just can't seem to figure it out.

如果我有一个包含ForeignKey的serializer在字段当该序列化程序嵌套在相关对象中时如何排除该FK?

If I've got a serializer with a ForeignKey included in its fields how do I exclude that FK when that serializer is nested in the related object?

class EmployerSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Employer
        fields = ('name', 'person')

class PersonSerializer(serializers.HyperlinkedModelSerializer):
    employers = EmployerSerializer()

    class Meta:
        model = Person
        fields = ('name', 'employers')
        depth = 1

当我在 http ://0.0.0.0:8000 / person / 1 / 它列出如下:

{
    "name": "Joe Blow",
    "employers": {
        "name": "Acme Inc."
        "person": "http://0.0.0.0:8000/person/1/"
        }
}

雇主的个人键是自引用和冗余的,但只有当序列化程序嵌套在对象中时才引用。

The "person" key for "employers" is self-referential and redundant, but only when the serializer is nested within the object it's referring to.

似乎应该有一个选项来排除它,当序列化程序是嵌套的,但我无法弄清楚。

It seems like there should be an option to exclude it when the serializer is nested, but I can't figure it out.

推荐答案

class DynamicFieldsModelSerializer(serializers.HyperlinkedModelSerializer):
    """
    A HyperlinkedModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)
        exclude = kwargs.pop('exclude', None)
        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        if fields:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)
        if exclude:
            # Drop fields that are specified in the `exclude` argument.
            excluded = set(exclude)
            for field_name in excluded:
                try:
                    self.fields.pop(field_name)
                except KeyError:
                    pass

使用DynamicFieldsModelSerializer扩展EmployerSerializer

extend EmployerSerializer with DynamicFieldsModelSerializer

class EmployerSerializer(DynamicFieldsModelSerializer):
    class Meta:
       model = Employer
       fields = ('name', 'person')


class PersonSerializer(serializers.HyperlinkedModelSerializer):
    employers = EmployerSerializer(exclude=('name',))
    class Meta:
        model = Person
        fields = ('name', 'employers')
        depth = 1

这篇关于当使用Django REST框架时,序列化程序嵌套时,如何排除父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆