使用Django Rest框架进行发布时出现AssertionError 发生错误之前的过程是这样
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',
]
http://127.0.0.1:8000/post/
3。发布
4。发生如下错误
感谢让我知道如何解决
答案 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)