gpt4 book ai didi

Django Rest Framework - 调用 "Got a ` 时出现 `Note.objects.create()' TypeError`

转载 作者:行者123 更新时间:2023-12-04 03:05:28 25 4
gpt4 key购买 nike

当我尝试使用 DRF 的可浏览 API 进行 POST 时,出现以下错误:

Got a TypeError when calling Note.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Note.objects.create(). You may need to make the field read-only, or override the NoteSerializer.create() method to handle this correctly.



我不知道是什么导致了这个错误或如何克服它。从字面上花几个小时谷歌搜索或更改代码。有人可以解释如何克服这个错误吗? (请注意,我是 Django 和 DRF 的新手!)

这是 models.py :
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
import uuid

class Stock(models.Model):
'''
Model representing the stock info.
'''
user = models.ForeignKey(User)
book_code = models.CharField(max_length=14, null=True, blank=True)

def __str__(self):
return self.book_code

class Note(models.Model):
'''
Model representing the stock note.
'''
user = models.ForeignKey(User)
note = models.TextField(max_length=560)
stock = models.ForeignKey(Stock, related_name='notes')
date_note_created = models.DateTimeField(default=timezone.now)

def __str__(self):
return self.note

这是 views.py :
from rest_framework import generics
from stocknoter.models import Stock, Note
from api.serializers import StockSerializer, NoteSerializer

# Create your views here.

class StockList(generics.ListCreateAPIView):
serializer_class = StockSerializer
def get_queryset(self):
user = self.request.user
return Stock.objects.filter(user=user)

def perform_create(self, serializer):
serializer.save(user=self.request.user)

def perform_update(self, serializer):
serializer.save(user=self.request.user)


class NoteList(generics.ListCreateAPIView):
serializer_class = NoteSerializer
def get_queryset(self):
user = self.request.user
return Note.objects.filter(user=user)

def perform_create(self, serializer):
serializer.save(data=self.request.data)

def perform_update(self, serializer):
serializer.save(data=self.request.data)

这是 serializers.py :
from stocknoter.models import Stock, Note
from rest_framework import serializers

class StockSerializer(serializers.ModelSerializer):
user = serializers.HiddenField(default=serializers.CurrentUserDefault())
notes = serializers.PrimaryKeyRelatedField(read_only=True)


class Meta:
model = Stock
fields = ('id', 'user', 'book_code', 'notes')

class NoteSerializer(serializers.ModelSerializer):
user = serializers.HiddenField(default=serializers.CurrentUserDefault())

class Meta:
model = Note
fields = ('user', 'note', 'stock')

最佳答案

我认为这是因为您提供了关键字参数 data保存方法。这是不必要的。 save()没有这样的论点。试试这个:

def perform_create(self, serializer):
serializer.save()

关于Django Rest Framework - 调用 "Got a ` 时出现 `Note.objects.create()' TypeError`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44997315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com