[英]How to get current user id in Django Rest Framework serializer
I have a serializer that gets product date from a table and the inventory data from another table for the user that is logged in. I have set up the serializer to get the product data and added fields which should hold the user's inventory amount.我有一个序列化程序,它从一个表中获取产品日期,并从另一个表中获取已登录用户的库存数据。我已经设置了序列化程序来获取产品数据并添加了应该保存用户库存量的字段。
The request returns the correct data structure, however it was returning the inventory amount for all users and then failing.该请求返回正确的数据结构,但是它返回所有用户的库存量然后失败。 So I have tried to filter these added fields by the current users id, however when adding it it fails.所以我试图通过当前用户 ID 过滤这些添加的字段,但是添加它时失败了。
I would like to filter the added fields for the user's inventory by the user id for the user that is logged in. However adding it seems to break the request.我想通过登录用户的用户 ID 过滤用户清单的添加字段。但是添加它似乎会破坏请求。
class CardsDataSerializers(serializers.ModelSerializer):
inventory = serializers.SerializerMethodField()
class Meta:
model = magic_set_cards
fields = ['id', 'name', 'rarity', 'manaCostList', 'convertedManaCost', 'colors', 'number', 'type', 'types', 'imageUri', 'promoTypes', 'hasFoil', 'hasNonFoil', 'inventory']
@staticmethod
def get_inventory(self, obj):
user_id = self.request.user.id
try:
standard = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('standard').get()[0]
except inventory_cards.DoesNotExist:
standard = 0
try:
foil = inventory_cards.objects.filter(user_id=user_id).filter(card_id=obj.id).values_list('foil').get()[0]
except inventory_cards.DoesNotExist:
foil = 0
inventory = {
'standard': standard,
'foil': foil,
}
return inventory
Error:错误:
get_inventory() missing 1 required positional argument: 'request'
Request Method: GET
Request URL: http://127.0.0.1:8000/magic/sets/ss1/cards-data/?name=
Django Version: 3.2.7
Exception Type: TypeError
Exception Value:
get_inventory() missing 1 required positional argument: 'request'
change the function from将 function 从
@staticmethod
def get_inventory(self, obj):
user_id = self.request.user.id
to到
def get_inventory(self, obj):
user = self.context['request'].user
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.