я пытаюсь использовать метод POST здесь, но он выдает ошибку.
это Models.py:
from django.db import models
class Post(models.Model):
post_text=models.CharField(max_length=200)
def __str__(self):
return self.post_text
class Choice(models.Model):
post=models.ForeignKey(Post, on_delete=models.CASCADE)
choice_text=models.CharField(max_length=200)
likes=models.IntegerField(default=0)
def __str__(self):
return self.choice_text
это serializes.py:
from rest_framework import serializers
from snippets.models import Post, Choice
class PostSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=Post
fields=['id','post_text']
class ChoiceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=Choice
fields=['id','choice_text','likes']
это views.py:
from django.shortcuts import render
from rest_framework import generics
from rest_framework.reverse import reverse
from .models import Choice, Post
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from snippets.serializers import ChoiceSerializer, PostSerializer
class PostList(generics.ListCreateAPIView):
queryset=Post.objects.all()
serializer_class=PostSerializer
name='post-list'
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
queryset=Post.objects.all()
serializer_class=PostSerializer
name='post-detail'
class ChoiceList(generics.ListCreateAPIView):
queryset=Choice.objects.all()
serializer_class=ChoiceSerializer
name='choice-list'
class ChoiceDetail(generics.RetrieveUpdateDestroyAPIView):
queryset=Choice.objects.all()
serializer_class=ChoiceSerializer
name='choice-detail'
class ApiRoot(generics.GenericAPIView):
name='api-root'
def get(self, request, *args, **kwargs):
return Response({
'posts': reverse(PostList.name, request=request),
'choices': reverse(ChoiceList.name, request=request),
})
urls.py:
urlpatterns=[
path('post-list/', views.PostList.as_view(), name='post-list'),
path('post-list/<int:pk>/', views.PostDetail.as_view()),
path('choice-list/', views.ChoiceList.as_view(), name='choice-list'),
path('choice-list/<int:pk>/', views.ChoiceDetail.as_view()),
path('',views.ApiRoot.as_view(),name=views.ApiRoot.name),
]
, когда я пытаюсь опубликовать сообщение:
{
"id":3
"choice_text": "random text",
"likes": 0
}
Я получил эту ошибку:
IntegrityError at /choice-list/
NOT NULL constraint failed: snippets_choice.post_id
, если я предоставляю идентификатор, почемувыдает ошибку?
даже в Почтальоне, он просит меня поставить 'choice_text', даже когда я предоставляю choice_text.