简体   繁体   English

使用Django REST Framework序列化外键数组

[英]Serializing an array of foreign keys with Django REST Framework

I have a model with custom "ArrayField" (for a Postgres array field), which stores an array of foreign keys to another model. 我有一个带有自定义“ ArrayField”的模型(用于Postgres数组字段),该模型将外键数组存储到另一个模型。 Django doesn't enforce the relation, but what I put in there are foreign keys. Django没有强制执行该关系,但是我输入的是外键。

class Foo(model):
    bars  =  ArrayField(models.IntegerField())

class Bar(model):
    blah  = models.CharField()

So the value of the 'bars' field is like [3,64,7,34,...] where the numbers are non-enforced foreign keys to Bar. 因此,“ bars”字段的值类似于[3,64,7,34,...] ,其中数字是Bar的非强制外键。 When rendering Foos, I'd like to render the related objects represented in this field using Django REST Framework: 渲染Foos时,我想使用Django REST Framework渲染此字段中表示的相关对象:

{ "foo" : {  "bars" : [ {"blah":"asdf"},
                        {"blah":"asdf"}
                      ]
          }
}

I'm having trouble figuring out how that should be expressed in the serializer: 我在弄清楚应该如何在序列化器中表达它有麻烦:

class BarSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('blah')

    blah     = serializersCharField()


class FooSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('bars')

    # bars     = BarSerializer(many=True)
    bars      = SomeSpecialCustomField() #?

How can I get JSON as above when rendering? 渲染时如何如上所述获取JSON?

Try playing around with this: 尝试玩这个:

class SomeSpecialCustomField(serializers.Field):

    def to_native(self, value):
        queryset = Bar.objects.filter(pk__in=value)
        serializer = BarSerializer(queryset, many=True)
        return serializer.data

Make sure you put proper validations, like checking if the value is a list etc. 确保进行适当的验证,例如检查值是否为列表等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM