Django Rest Framework在POST中接收主键值,并以嵌套序列化程序的形式返回模型对象 [英] Django Rest Framework receive primary key value in POST and return model object as nested serializer

查看:215
本文介绍了Django Rest Framework在POST中接收主键值,并以嵌套序列化程序的形式返回模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能完全确定我的问题的标题是否像我想要的那样具体,但这是事实:

I'm not completely sure that the title of my question is as specific as I wanted it to be, but this is the case:

我有一个看起来像这样的HyperlinkedModelSerializer:

I have a HyperlinkedModelSerializer that looks like this:

class ParentArrivalSerializer(serializers.HyperlinkedModelSerializer):
    carpool = SchoolBuildingCarpoolSerializer()

    class Meta:
        model = ParentArrival

如您所见,carpool被定义为嵌套的序列化程序对象,而我想要的是能够发出POST请求以这种方式创建ParentArrival(数据为application/json):

As you can see the carpool is defined as a nested serializer object and what I want is to be able to make a POST request to create a ParentArrival in this way (data as application/json):

{
    ...
    "carpool": "http://localhost:8000/api/school-building-carpools/10/"
    ...
}

并以这种方式接收数据:

And receive the data in this way:

{
    "carpool": {
        "url": "http://localhost:8000/api/school-building-carpools/10/"
        "name": "Name of the carpool",
        ...
    }
}

基本上,我正在寻找一种处理嵌套的序列化器的方法,而不必在POST请求中将数据作为对象发送(在这种情况下为id或url),而是将对象作为嵌套在序列化响应中的对象来接收. /p>

Basically, I'm looking for a way to deal with nested serializers without having to send data as an object (but id or url in this case) in POST request, but receiving the object as nested in the serialized response.

推荐答案

我对以前的解决方案感到满意,但决定再次查看,我认为我有另一种解决方案完全可以满足您的需求.

I have been happy with my previous solution, but decided to look again and I think I have another solution that does exactly what you want.

基本上,您需要创建自己的自定义字段,然后覆盖to_representation方法:

Basically, you need to create your own custom field, and just overwrite the to_representation method:

class CarpoolField(serializers.PrimaryKeyRelatedField):
    def to_representation(self, value):
        pk = super(CarpoolField, self).to_representation(value)
        try:
           item = ParentArrival.objects.get(pk=pk)
           serializer = CarpoolSerializer(item)
           return serializer.data
        except ParentArrival.DoesNotExist:
           return None

    def get_choices(self, cutoff=None):
        queryset = self.get_queryset()
        if queryset is None:
            return {}

        return OrderedDict([(item.id, str(item)) for item in queryset])

class ParentArrivalSerializer(serializers.HyperlinkedModelSerializer):
    carpool = CarpoolField(queryset=Carpool.objects.all())

    class Meta:
        model = ParentArrival

这将使您可以发帖

{
     "carpool": 10
}

并获得:

{
    "carpool": {
        "url": "http://localhost:8000/api/school-building-carpools/10/"
        "name": "Name of the carpool",
        ...
    }
}

这篇关于Django Rest Framework在POST中接收主键值,并以嵌套序列化程序的形式返回模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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