django rest framework 序列化程序将字段值保存为空字符串,但没有错误

django rest framework serializer saving field value as empty strings, but no errors

django rest framework 序列化程序将字段值保存为空字符串,但没有错误

views.py

from django.shortcuts import render
from rest_framework import viewsets

from rest_framework.authentication import TokenAuthentication

from .models import MyTodo
from .serializers import  MyTodoSerializer


class MyTodoView(viewsets.ModelViewSet):

    queryset = MyTodo.objects.all()
    serializer_class = MyTodoSerializer

我的模特是

models.py

from django.db import models

# Create your models here.

class MyTodo(models.Model):
    # Autoincrement id
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=200, blank=True, default='')
    description = models.CharField(max_length=20, blank=True, default='')
    created_on = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

我的序列化器是

serializers.py

from rest_framework import serializers
from mytodo.models import MyTodo

class MyTodoSerializer( serializers.ModelSerializer ):

    title = serializers.CharField(max_length=200, default='')
    description = serializers.CharField(max_length=200, default='')
    created_on = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S", required=False)

    def create(self, validated_data):
        return MyTodo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.title = validated_data.get('title', instance.title)
        instance.description = validated_data.get('description', instance.description)
        instance.created_on = validated_data.get('created_on', instance.created_on )
        instance.save()
        return instance


    class Meta:
        model = MyTodo
        fields = [ 'id','url','title','description', 'created_on' ]

看起来很简单,直接但通过 CURL 调用保存空字段,但可浏览 API 视图工作得很好。请告诉我我做错了什么。

这是我正在尝试做的事情

Curl 客户端

#!/bin/bash

b64credential=$(echo 'admin:admin' | base64)

access_token=$(curl -d "username=admin&password=admin"  -X POST 'http://localhost:8000/api/token/' \
-H 'Accept:application/json' \
-H "Authorization:Basic  ${b64credential}" | jq --raw-output '.access' )

echo "Access token : $access_token"

# post a todo to  mytodo api

curl -vvv -L -d '{"title": "Awesome things to be done" ,"description": "Really great things stay alert"}' \
     -X POST 'http://localhost:8000/mytodo/' \
     -H 'Accept:application/json' \
     -H "Authorization:Bearer  ${access_token}"

响应看起来像这样

{"id":23,"url":"http://localhost:8000/mytodo/23/","title":"","description":"","created_on":"2021-05-14T10:02:45"}

还有几个问题

  1. 为什么我得到标题:"",描述:"",

  2. 在视图中,我只有 serializer_class = MyTodoSerializer 没有关于实际请求处理的信息,Django 如何正确调用正确的方法 MyTodoSerializer.create()

您已将 '' 设置为默认值,并且 cURL 负载未传递给 Django。

原因是你的header不对。

     -H 'Accept:application/json' \

应该是

     -H "Content-Type: application/json"

试试这个。

curl -vvv -L -d '{"title": "Awesome things to be done" ,"description": "Really great things stay alert"}' -X POST 'http://localhost:8000/mytodo/' -H "Content-Type: application/json" -H "Authorization:Bearer  ${access_token}"

这两个header的区别可以找到here.