python django-rest-framework 3.3.3 更新嵌套序列化程序

Posted

技术标签:

【中文标题】python django-rest-framework 3.3.3 更新嵌套序列化程序【英文标题】:python djaango-rest-framework 3.3.3 update nested serializer 【发布时间】:2017-01-28 20:56:50 【问题描述】:

使用 django-rest 框架 3.3.3

我正在尝试使用 django-rest 框架更新我的数据库中的现有数据,遵循之前发布的解决方案:django-rest-framework 3.0 create or update in nested serializer

总的来说,我对 django 和其他框架还很陌生。

鉴于以下模型:

class Clinic(models.Model):

    name = models.TextField()
    streetNumber = models.IntegerField()
    unitNumber = models.CharField(max_length=10, blank=True, null=True)
    streetName = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    province = models.CharField(max_length=3)
    country = models.CharField(max_length=30)
    postalCode = models.CharField(max_length=6)
    phone = models.CharField(max_length=10)

    def __str__(self):
        return self.name


class Time (models.Model):

     clinic = models.ForeignKey(Clinic, related_name='times')
     appointmentTime = models.CharField(max_length=100)

     def __str__(self):
         return self.appointmentTime

以及以下序列化程序:

class TimeSerializer(serializers.ModelSerializer):

    class Meta:
        model = Time
        fields = ('appointmentTime',)


class ClinicSerializer(serializers.ModelSerializer):

    times = TimeSerializer(many=True)

    class Meta:
        model = Clinic
        fields = '__all__'

    def update(self, instance, validated_data):

        instance.name = validated_data['name']
        instance.streetName = validated_data['streetName']
        instance.unitNumber = validated_data['unitNumber']
        instance.city = validated_data['city']
        instance.province = validated_data['province']
        instance.country = validated_data['country']
        instance.postalCode = validated_data['postalCode']
        instance.phone = validated_data['phone']
        #print(instance)
        instance.save()

        times_data = [item['id'] for item in validated_data['times']]
        print(times_data)
        for time in instance.clinics:
            if time.id not in times_data:
                time.delete()

        for item in validated_data['times']:
            time = Time(id=item['id'], clinic=instance,
            appointmentTime=item['appointmentTime'])
            time.save()

        return instance

还有以下观点:

class ClinicList(APIView):

def get(self,request):
    clinics = Clinic.objects.all()
    serializer = ClinicSerializer(clinics, many=True)
    return Response('results': serializer.data)

def post(self, request):

    serializer = ClinicSerializer(data=request.data)
    if serializer.is_valid():

        serializer.update(Clinic, serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

以及以下现有数据:


        "id": 2,
        "times": [
            
                "appointmentTime": "time3"
            ,
            
                "appointmentTime": "time3"
            
        ],
        "name": "Example Clinic",
        "streetNumber": 123,
        "unitNumber": "",
        "streetName": "Example Street",
        "city": "Exampletown",
        "province": "Ont",
        "country": "Canada",
        "postalCode": "A1A1A1",
        "phone": "9059059059"
    

我的 JSON POST 数据是:


        "id": 2,
        "times": [
            
                "appointmentTime": "AAAA"
            ,
            
                "appointmentTime": "time3"
            
        ],
        "name": "Example Clinic",
        "streetNumber": 123,
        "unitNumber": "",
        "streetName": "Example Street",
        "city": "Exampletown",
        "province": "Ont",
        "country": "Canada",
        "postalCode": "A1A1A1",
        "phone": "9059059059"
    

我的问题是我收到一条错误消息:

文件“C:\Users\colin\Documents\GitHub\Walk_inExpressAPI\clinics\serializer.py”,

第 31 行,更新中

instance.save()

TypeError: save() 缺少 1 个必需的位置参数:'self'

我不确定我在这里做错了什么,或者为 instance.save() 提供什么值来纠正这个错误。我已经检查过该实例是 Clinic 类型的对象。

我想要完成的是每个诊所可以有多个预约时间。他们不会共享约会时间对象,因为我希望能够在每次预订新约会时删除一个约会时间,并且每个诊所都需要自己的一组可用约会时间。

希望你们能帮助我朝着正确的方向前进!谢谢!

【问题讨论】:

【参考方案1】:

您应该在您的APIView 中使用PUT 方法:

def put(self, request, pk):
   clinics = Clinic.objects.get(pk=pk)
   serializer = ClinicSerializer(clinics, data=request.data)
   if serializer.is_valid():
       serializer.save()
       return Response(serializer.data)
   return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

所以在你的 url.py 中应该有一个 pk,用来标识你要修改的对象:

urlpatterns = [
    url(r'^snippets/$', views.ClinicList.as_view()),
    url(r'^snippets/(?P<pk>[0-9]+)/$', views.ClinicList.as_view()),
]

在更新方法中更改实例属性,如:

instance.name = validated_data.get('name',instance.name)

也尝试查看DRF page 中的示例。

【讨论】:

以上是关于python django-rest-framework 3.3.3 更新嵌套序列化程序的主要内容,如果未能解决你的问题,请参考以下文章

尽管字段具有“空白=真”,但 Django EmbeddedModelField 在执行 PUT 请求时说“此字段可能不是空白”

代写python,代写python编程,python代写,python编程代写,留学生python代写

001--python全栈--基础知识--python安装

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python