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)
答案 0 :(得分:1)
我通过不从Object获取所有值来解决我的问题。 了解ORM的基础知识:)
在我看来,我从这个
改变了这一行user_skill_upvotes = list(UserSkillUpvotes.objects.filter(upvote_for=pk).all().values()) # get all upvotes on skills of the requested user
到这个
user_skill_upvotes = list(UserSkillUpvotes.objects.filter(upvote_for=pk))