如何在Django Rest Framework中的一个序列化程序中更新两个模型? [英] How can I update two models in one serializer in Django Rest Framework?

查看:130
本文介绍了如何在Django Rest Framework中的一个序列化程序中更新两个模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库架构,该架构的每个特定类型的对象都存储在两个单独的表中(每个表中的一行,每个表中的数据不同,并带有一个到另一个的外键。)

I have a database schema that has each object of a certain type being stored across two separate tables (one row in each table, different data in each, with a foreign key from one to the other.)

不幸的是,Django Rest Framework倾向于假定序列化程序和模型之间存在一对一的对应关系,这在我的情况中是不正确的。我应该如何处理呢?似乎序列化程序应该返回对象的表示形式,这将是ajax请求的实际HTTP响应,因此使用两个序列化程序似乎并不正确。我已经研究了扩展BaseSerializer(如果我找不到更好的解决方案,这是我目前计划实现的方式),但是某些方法采用了 instance ,包含序列化对象所需的所有数据,而我有两个相关的实例。

Unfortunately, Django Rest Framework tends to assume that there is a one to one correspondence between serializers and models, which is not true of my case. How should I be approaching this? It seems like the serializer should return the representation of the object which will be the actual HTTP response of the ajax requests, so using two serializers doesn't seem right. I've looked at extending BaseSerializer (which is how I currently plan to implement this if I don't find better solutions), but certain methods take in an instance, which should contain all the data needed to serialize the object, whereas I have two instances relevant.

任何建议将不胜感激!谢谢。

Any advice would be super appreciated! Thank you.

推荐答案

可写的嵌套表示法部分可能会对您有所帮助。

Writable nested representations section might help you.

您有2个模型 ModelA ModelB 。创建第一个模型的序列化器

You have 2 models ModelA and ModelB. Create your first model's serializer

class ModelASerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelA
        fields = ('fields',..) # 

然后在其他模型的序列化器中添加第一个序列化程序并覆盖所需的方法(例如 create update )。像这样:

Then in other model's serializer add the first serializer and override the required methods (like create, update). Something like this:

class ModelBSerializer(serializers.ModelSerializer):
    # add the serializer for the foreignkey model 
    model_a = ModelASerializer()   

    class Meta:
        model = ModelB
        fields = ('fields',..) # 

   def create(self, validated_data):
       modela_data = validated_data.pop('model_a')
       model_b = ModelB.objects.create(**validated_data)
       ModelA.objects.create(model_b=model_b, **modela_data)
       return model_b

   # override update too ..

这篇关于如何在Django Rest Framework中的一个序列化程序中更新两个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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