我想创建一个带有外键 request.user
的 SpiderService
。
模型:
from django.contrib.auth.models import User
class SpiderService(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=20)
序列化器:
class SpiderServiceSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.id')
class Meta:
model = SpiderService
fields = ('id', 'user', 'name')
class SpiderServiceListSerializer(viewsets.ModelViewSet):
queryset = SpiderService.objects.all()
serializer_class = SpiderService
观看次数:
class SpiderServiceList(APIView):
def get(self, request, format=None):
services = SpiderService.objects.all()
serializer = SpiderServiceSerializer(services, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = SpiderServiceSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def perform_create(elf, serializer):
serializer.save(user=self.request.user)
当我发帖时
{
"name": "2"
}
到 api url,出现 500 错误:
[01/Feb/2016 15:39:55] "POST /services/ HTTP/1.1" 500 17105
IntegrityError: NOT NULL constraint failed: spmanage_spiderservice.user_id
我已阅读 Serializer relations发现我不应该像上面那样写代码。官方的例子相当于去掉了SpiderServiceSerializer
中的user field
,在UserSerializer
中增加了一个spiderservice field
。貌似目标是在 django 模型中实现类似 user.spiderservice_set
的语法,这不符合我的目的。
我只想用 request.user
创建一个 spiderservice 对象。
如何解决?
我是一名优秀的程序员,十分优秀!