当我试图在视图的帖子()中保存模型对象(其名称为' RSS)时,它没有保存,如何保存模型实例' rss'从视图的帖子()?
在Serializers类中:
class RSSSerializer(serializers.ModelSerializer):
class Meta:
model = RSS
fields = ('feed_url', 'website_url', 'description', 'title')
def create(self, validated_data):
rss = RSS(**validated_data)
rss.created_at = datetime.now()
rss.last_scan_time = '2001-01-01 00:00:00'
rss.id = None
return rss
在View类中:
class RSSList(APIView):
def post(self, request):
serializer = RSSSerializer(data=request.data)
if serializer.is_valid():
print("saving rss post")
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
答案 0 :(得分:0)
您当前的create
方法会实例化一个新的RSS
对象,但不会保存它。试试这个:
def create(self, validated_data):
rss = RSS.objects.create(**validated_data)
rss.created_at = datetime.now()
...
return rss.save()
更多信息:Django rest framework: override create() in ModelSerializer passing an extra parameter
http://www.django-rest-framework.org/api-guide/serializers/#saving-instances
如果您的对象实例对应于Django模型,您还要确保这些方法将对象保存到数据库中。