如何在Django REST框架中将过滤器应用于嵌套资源? [英] How can I apply a filter to a nested resource in Django REST framework?
问题描述
在我的应用程序中,我有以下模型:
In my app I have the following models:
class Zone(models.Model):
name = models.SlugField()
class ZonePermission(models.Model):
zone = models.ForeignKey('Zone')
user = models.ForeignKey(User)
is_administrator = models.BooleanField()
is_active = models.BooleanField()
我是使用Django REST框架创建返回区域详细信息的资源以及显示该区域的已验证用户权限的嵌套资源。输出应该是这样的:
I am using Django REST framework to create a resource that returns zone details plus a nested resource showing the authenticated user's permissions for that zone. The output should be something like this:
{
"name": "test",
"current_user_zone_permission": {
"is_administrator": true,
"is_active": true
}
}
我已经创建了这样的序列化:
I've created serializers like so:
class ZonePermissionSerializer(serializers.ModelSerializer):
class Meta:
model = ZonePermission
fields = ('is_administrator', 'is_active')
class ZoneSerializer(serializers.HyperlinkedModelSerializer):
current_user_zone_permission = ZonePermissionSerializer(source='zonepermission_set')
class Meta:
model = Zone
fields = ('name', 'current_user_zone_permission')
这个问题是当我请求一个特定的区域时,嵌套的资源会返回ZonePermission记录,强>用户用该区的任务。有没有办法在 request.user
上将过滤器应用于嵌套资源?
The problem with this is that when I request a particular zone, the nested resource returns the ZonePermission records for all the users with permissions for that zone. Is there any way of applying a filter on request.user
to the nested resource?
BTW我不想要使用 HyperlinkedIdentityField
(以尽量减少http请求)。
BTW I don't want to use a HyperlinkedIdentityField
for this (to minimise http requests).
这是我根据以下答案实现的解决方案。我将以下代码添加到序列化器类中:
This is the solution I implemented based on the answer below. I added the following code to my serializer class:
current_user_zone_permission = serializers.SerializerMethodField('get_user_zone_permission')
def get_user_zone_permission(self, obj):
user = self.context['request'].user
zone_permission = ZonePermission.objects.get(zone=obj, user=user)
serializer = ZonePermissionSerializer(zone_permission)
return serializer.data
非常感谢解决方案!
推荐答案
我面对同样的情况。我发现最好的解决方案是使用一个 SerializerMethodField
,并使用该方法查询并返回所需的值。您可以通过 self.context ['request']。
访问 request.user
。
I'm faced with the same scenario. The best solution that I've found is to use a SerializerMethodField
and have that method query and return the desired values. You can have access to request.user
in that method through self.context['request'].user
.
但是,这似乎是一个黑客。我对DRF来说相当新鲜,所以也许有更多经验的人可以进入。
Still, this seems like a bit of a hack. I'm fairly new to DRF, so maybe someone with more experience can chime in.
这篇关于如何在Django REST框架中将过滤器应用于嵌套资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!