[英]Integrity error in django foreign key field in django-rest-framework
I'm fairly new in django. 我在django还很新。 I've had a foreignkey field as supervisor as shown below
我有一个外键字段作为主管,如下所示
class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return "{}".format(self.sitename)
The serializer for this is: 为此的序列化器是:
class SiteSerializer(serializers.ModelSerializer):
supervisor = serializers.ReadOnlyField(source='supervisor.username')
class Meta:
model = Site
fields = ('sitename', 'start_date', 'supervisor')
and the view for this is: 对此的视图是:
@csrf_exempt
def site_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
sites = Site.objects.all()
serializer = SiteSerializer(sites, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SiteSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
Whenever I post data from postman, it says IntegrityError at /sites/ (1048, "Column 'supervisor_id' cannot be null")
I named the model field as supervisor and the db field becomes supervisor_id as django does it. 每当我从邮递员发布数据时,它都会
IntegrityError at /sites/ (1048, "Column 'supervisor_id' cannot be null")
我将模型字段命名为supervisor,而db字段则像django一样变为supervisor_id。 But,how do I sort this error out. 但是,我该如何解决该错误。 This might be a really little thing but I couldnt figure out where to make the nexessary adjustments.
这可能是一件很小的事情,但我无法弄清楚在哪里做出调整。 Please help.
请帮忙。
My post request is { "sitename" : "Tony Tower", "start_date" :"2019-5-5", "supervisor" : "1" }
OR 我的发帖请求是
{ "sitename" : "Tony Tower", "start_date" :"2019-5-5", "supervisor" : "1" }
或
{
"sitename" : "Putalisadak",
"start_date" :"2019-5-5",
"supervisor_id" : "1"
}
both yielding the same output 两者产生相同的输出
Django expects you to pass a User object and not an id as you did, which is why it is throwing the integrity error. Django希望您传递User对象而不是像过去那样传递id,这就是为什么它引发完整性错误。 For example, if supervisor is current user it should be
serializer.save(supervisor=request.user)
例如,如果主管是当前用户,则应为
serializer.save(supervisor=request.user)
Ps: Typed this using my phone, hope I got the code markup correct. 附:使用手机输入此内容,希望我的代码标记正确。
try with: 尝试:
{
"sitename" : "Tony Tower",
"start_date" :"2019-5-5",
"supervisor__id" : "1"
}
我认为错误就在这行:超级用户= serializers.ReadOnlyField(source ='supervisor.username')您是否尝试将其删除?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.