![](/img/trans.png)
[英]Django Rest Framework - CreateAPIView ForeignKey lookup fields
[英]Django REST Framework - Serialize ForeignKey fields
在我的應用中,用戶有一堵牆,類似於舊的Facebook牆。 用戶可以在其他用戶的牆上張貼評論。 我有一個具有以下基本結構的序列化器:
class UserWallCommentSerializer(serializers.ModelSerializer):
class Meta:
model = UserWallComment
fields = ('uid', 'uidcommenter', 'idwall', 'created', 'description')
read_only_fields = ('uid', 'uidcommenter', 'idwall', 'created')
uid
和uidcommenter
是用戶模型的外鍵, idwall
是PK, description
是注釋本身。
創建/編輯注釋時,后端需要設置uid
和uidcommenter
。 不允許用戶更改這些字段。
可以說我在調用序列化程序的視圖中有變量uid
和uidcommenter
如何將這些變量傳遞給序列化程序,以便創建UserWallComment?
我嘗試使用SerializerMethodField
設置uid
和uidcommenter
(在上下文變量中傳遞PK),但是數據庫說我傳遞了NULL PK:
class UserWallCommentSerializer(serializers.ModelSerializer):
uid = serializers.SerializerMethodField('setUid')
class Meta:
model = UserWallComment
fields = ('uid', 'uidcommenter', 'idwall', 'created', 'description')
read_only_fields = ('uidcommenter', 'idwall', 'created')
def setUid(self):
return self.context['uid']
我的查看代碼( idwall
是牆的pk):
class MemberWall(APIView):
def post(self, request, requestUid, idwall):
uid = request.user.uid
serializer = UserWallCommentSerializer(data=request.DATA, context={'uid': requestUid, 'uidcommenter': uid})
if serializer.is_valid():
serializer.save()
return Response(serializer.data['uid'], status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
該文檔說SerializerMethodField
僅用於對象的表示 。 這意味着僅當您返回數據作為響應時才使用它。
默認情況下,序列化器獲取傳遞的請求:
def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}
這意味着您可以覆蓋默認的保存,更新序列化程序的方法並設置相關字段。 然后,您應該可以使用: self._context.request.user.uid
進行訪問
我沒有嘗試過,但是應該可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.