简体   繁体   中英

Integrity error in django foreign key field in django-rest-framework

I'm fairly new in 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. 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" : "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. For example, if supervisor is current user it should be 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')您是否尝试将其删除?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM