Django rest框架一对一关系 [英] Django rest framework one to one relation

查看:160
本文介绍了Django rest框架一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下模型:

class A(models.Model):
  name = models.CharField()
  age = models.SmallIntergerField()

class B(models.Model):
  a = models.OneToOneField(A)
  salary = model.IntergerField()

现在,我想为其中两个创建一个休止点,因为它们是一对一的。因此,我想作为get

Now I want to create one rest end point for there two as they are one to one. So I want following as get

{
  url: 'http://localhost/customs/1/',
  name: 'abc',
  age: 24,
  salary: 10000
}

Similary,我也想创建记录并更新。请让我知道如何在django rest框架3中实现此目标。

Similary, I want to create records and update as well. Please let me know how can I achieve this in django rest framework 3.

推荐答案

我刚刚遇到了相同的问题,实际上有助于使响应结构与基础模型结构的联系减少。这是我的看法:

I just encountered the same problem, it would indeed be useful to make the response structure less tied to the underlying model structure. Here's my take :

序列化器字段具有 source 参数,该参数可以

Serializer fields have a source parameter, which can take dotted names to traverse attributes.

class ABSerializer(serializers.ModelSerializer):

    class Meta:
        model = A
        fields = ['name', 'age', 'salary']

    salary = serializer.IntegerField(source='b.salary') # this is your related_name



文字...不被正式支持



验证的数据将显示一个嵌套结构,而标准的create和update方法将阻止尝试将数据dict分配给OneToOneField。
好​​消息是您可以通过覆盖创建和更新方法。这是一个带有update的示例:

Writing is ... not officially supported

Validated data will show a nested structure, and the standard create and update methods will choke trying to assign a data dict to a OneToOneField. The good news is that you can work around it by overriding create and update methods. Here's an example with update :

class ABSerializer(serializers.ModelSerializer):

    class Meta:
        model = A
        fields = ['name', 'age', 'salary']
        related_fields = ['b']

    salary = serializer.IntegerField(source='b.salary') # this is your related_name

    def update(self, instance, validated_data):
        # Handle related objects
        for related_obj_name in self.Meta.related_fields:

            # Validated data will show the nested structure
            data = validated_data.pop(related_obj_name)
            related_instance = getattr(instance, related_obj_name)

            # Same as default update implementation
            for attr_name, value in data.items():
                setattr(related_instance, attr_name, value)
            related_instance.save()
        return super(ABSerializer,self).update(instance, validated_data)

当然,此示例非常简单,不执行任何异常处理,并赢得了不能与更深层嵌套的对象一起使用...但是您知道了。

Of course, this example is very simplistic, doesn't do any exception handling, and won't work with more deeply nested objects... but you get the idea.

您还可以创建具有Seri​​alizerMethodField的读写样式,它将同时考虑getter和setter,但最终可能会

You could also create a read-write flavor of SerializerMethodField, which would consider both a getter and a setter, however that would probably end up being far more verbose in the end.

希望有帮助!

这篇关于Django rest框架一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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