无法使用Django restframework将最后一个insert_id从父序列化器传递给子序列化器

时间:2019-01-30 19:03:09

标签: python-3.x django-rest-framework django-serializer

我正在尝试使用相同的api调用保存父(VisVisits)和子(VisVistiData)表。数据进入json格式。我可以在儿童(VisVisitData)表中保存除第一列visit_id以外的两个表。 visit_id并非来自json。这是父表(VisVisits)中的自动数字类型字段,我想从父表(插入后)中获取visit_id并将其与子表(VisVisitData)中的其他列一起保存到其子ID中。

我真的需要帮助来解决此问题。

序列化器

class VisVisitsSerializer(serializers.ModelSerializer):

    data = VisVisitDataSerializer(many=True)

    class Meta:
        model = VisVisits
        fields = ('visit_id','user','data')
        read_only_fields = ['visit_id']

    def create(self, validated_data):
        visits_data = validated_data.pop('data')
        visit = VisVisits.objects.create(**validated_data)
        for visit_data in visits_data:
            VisVisitData.objects.create(visit_id=visit.visit_id, **visit_data)
        return visit


class VisVisitDataSerializer(serializers.ModelSerializer):
    class Meta:
        model = VisVisitData
        fields = ('__all__')

型号

class VisVisits(models.Model):
    visit_id = models.IntegerField(primary_key=True,auto_created=True)
    user = models.ForeignKey(UsrUsers, models.DO_NOTHING, blank=False, null=False)

    def __str__(self):
        return str(self.visit_id)

class VisVisitData(models.Model):
    vdata_id = models.IntegerField(primary_key=True,auto_created=True)
    visit = models.ForeignKey('VisVisits', models.DO_NOTHING, blank=True, null=True, related_name='data')

    def __str__(self):
        return str(self.vdata_id)

json

{
  "user": "1",
  "visits": [
    {
      "action": "i",
      "local_id": "170",

      "data": [
        {
          "Active": "1",
          "LocalID": "1905",
          "VisitDataID": "",
        },
        {
          "Active": "1",
          "LocalID": "1906",
          "VisitDataID": "",
        },
        {
          "Active": "1",
          "LocalID": "1907",
          "VisitDataID": "",
        },
        {
          "Active": "1",
          "LocalID": "1908",
          "VisitDataID": "",
        },
        {
          "Active": "1",
          "LocalID": "1909",
          "VisitDataID": "",
        }
    ]
}

0 个答案:

没有答案