问题描述
可以在模型序列化程序中获取当前用户吗?我想这样做,而不用分散泛型,因为这是一个简单的任务,必须完成。
Is it possible to get the current user in a model serializer? I'd like to do so without having to branch away from generics, as it's an otherwise simple task that must be done.
我的模型:
class Activity(models.Model):
number = models.PositiveIntegerField(
blank=True, null=True, help_text="Activity number. For record keeping only.")
instructions = models.TextField()
difficulty = models.ForeignKey(Difficulty)
categories = models.ManyToManyField(Category)
boosters = models.ManyToManyField(Booster)
class Meta():
verbose_name_plural = "Activities"
我的序列化程序:
class ActivitySerializer(serializers.ModelSerializer):
class Meta:
model = Activity
我的观点:
class ActivityDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Activity.objects.all()
serializer_class = ActivityDetailSerializer
如何获取返回的模型,附加字段用户
,使我的回复如下所示:
How can I get the model returned, with an additional field user
such that my response looks like this:
{
"id": 1,
"difficulty": 1,
"categories": [
1
],
"boosters": [
1
],
"current_user": 1 //Current authenticated user here
}
推荐答案
我通过Djangorestframework源代码找到答案。
I found the answer through the Djangorestframework source code.
class ActivitySerializer(serializers.ModelSerializer):
# Create a custom method field
current_user = serializers.SerializerMethodField('_user')
# Use this method for the custom field
def _user(self, obj):
user = self.context['request'].user
return user
class Meta:
model = Activity
# Add our custom method to the fields of the serializer
fields = ('id','current_user')
关键是在 ModelSerializer
中定义的方法可以访问他们自己的上下文,这个上下文总是包含请求(当一个被认证的时候它包含一个用户) )。由于我的权限仅适用于经过身份验证的用户,所以应该总是有些东西。
The key is the fact that methods defined inside a ModelSerializer
have access to their own context, which always includes the request (which contains a user when one is authenticated). Since my permissions are for only authenticated users, there should always be something here.
这也可以在其他内置的djangorestframework序列化器中完成。
This can also be done in other built-in djangorestframework serializers.
这篇关于在Model Serializer中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!