简体   繁体   中英

django - key error in serializer with foreign key models

I checked out all related questions but still curious to know if there exist an updated answer .

django serialize foreign key objects

So , I have a model which has three foreign keys , next when I am trying to GET a response using that model , they keys in List is appended with "_id" - so whenever I am serializing , I am getting the "KeyError at" error.

Error :

KeyError at /api/v1/user/skill/upvotes/1 'skill'

Model :

class UserSkillUpvotes(models.Model):
    unique_together = (('user_skill', 'upvote_by'),)
    skill = models.ForeignKey('Skill',on_delete=models.CASCADE , related_name='all_upvote_for_user_skill')
    upvote_by =  models.ForeignKey('auth.User',on_delete=models.CASCADE , related_name='all_upvote_by_user') 
    upvote_for = models.ForeignKey('auth.User',on_delete=models.CASCADE , related_name='all_upvote_for_user')

Serializer :

class UserSkillUpvotesSerializer(serializers.ModelSerializer):
    class Meta:
        model=UserSkillUpvotes
        fields='__all__'

View : if request.method == 'GET':

try:
    user_skill_upvotes = list(UserSkillUpvotes.objects.filter(upvote_for=pk).all().values()) # get all upvotes on skills of the requested user
except (UserSkillUpvotes.DoesNotExist,User.DoesNotExist) as e:
    return HttpResponse(status=404)
serializer = UserSkillUpvotesSerializer(user_skill_upvotes,many=True)
return Response(serializer.data)

Console error -

File "C:\code\django\wantedly\src\wantedly_webapp\views\AllViews.py", line 75, in user_skill_upvotes
  return Response(serializer.data)

I resolved my problem by not fetching all values from the Object . Learnt the basics of ORM :)

In my views I changed this line from this

user_skill_upvotes = list(UserSkillUpvotes.objects.filter(upvote_for=pk).all().values()) # get all upvotes on skills of the requested user

to this

 user_skill_upvotes = list(UserSkillUpvotes.objects.filter(upvote_for=pk))

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