使用Django Rest框架过帐时出现AssertionError

时间:2020-08-07 04:46:41

标签: django django-rest-framework

使用Django Rest框架进行发布时出现AssertionError 发生错误之前的过程是这样

  1. 我设置了网址格式,视图和序列化程序类
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import views

router = DefaultRouter()
router.register('post' , views.PostViewSet)
# print("router.urls : " , router.urls)

urlpatterns = [
    path('public/' , views.PublicPostListAPIView.as_view()),
    path('', include(router.urls)),
]


视图

from rest_framework import generics
from rest_framework.viewsets import ModelViewSet
from .serializers import PostSerializer
from .models import Post


class PublicPostListAPIView(generics.ListAPIView):
   queryset = Post.objects.filter(is_public=True)
   serializer_class = PostSerializer

class PostViewSet(ModelViewSet):
   queryset = Post.objects.all()
   serializer_class = PostSerializer

serializers.py

from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from instagram.models import Post

class AuthorSerializer(serializers.ModelSerializer):
   class Meta:
      model = get_user_model()
      fields = ['username','email']


class PostSerializer(ModelSerializer):
   author = AuthorSerializer()
   
   class Meta:
      model = Post
      fields = [
         'pk',
         'author',
         'message',
         'created_at',
         'updated_at',
         'is_public',

      ]
  1. 请求以下地址
http://127.0.0.1:8000/post/

3。发布

enter image description here

4。发生如下错误

enter image description here

感谢让我知道如何解决

1 个答案:

答案 0 :(得分:1)

假设要保存您在author中提供的PostSerializer详细信息。您可以像这样拥有自己的create()方法-

def create(self, validate_data):
    data = validated_data
    author = data.get('author')
    # You can use author details here
    data.pop('author')
    return Post.objects.create(**data)