为什么不将reste框架序列化器保存为两个不同的模型

时间:2015-10-08 10:25:13

标签: django django-models django-rest-framework

我希望序列化程序将数据保存到2个不同的模型:

from .models import Url1, Url2



class RushSerializer(serializers.ModelSerializer):    
    u2 = serializers.StringRelatedField(many=True)
    class Meta:
        model = Url1       
        fields = ('keyword', 'u1', 'keyword2', 'u2')  

以下是模特:

class Url1(models.Model):
    keyword = models.ForeignKey(KW)
    u1 = models.URLField()

class Url2(models.Model):
    keyword2 = models.ForeignKey(KW)
    u2 = models.URLField()

我要保存的字典:

{"keyword": 73, "u1": "https://www.pinterest.com/ercamacho/diy-headbands/",
  "keyword2": 71, "u2": "http://www.youtube.com/watch?v=9TWxSufCgvE"} 

如果我尝试保存到一个模型但我希望将数据保存在多个模型中,效果很好。

1 个答案:

答案 0 :(得分:1)

有两种型号,因此请使用serializers.Serializer并覆盖save()

class RushSerializer(serializers.Serializer):
    keyword = ...
    u1 = ...
    keyword2 = ...
    u2 = ...

    def save(self):
        keyword = self.validated_data['keyword']
        u1 = self.validated_data['u1']
        keyword2 = self.validated_data['keyword2']
        u2 = self.validated_data['u2']

        Url1.objects.create(keyword=keyword, u1=u1)
        Url2.objects.create(keyword2=keyword2, u2=u2)

请参阅http://www.django-rest-framework.org/api-guide/serializers/#saving-instances