如何根据请求用户使用自定义模型序列化程序限制相关字段的查询集? 我用SerializerMethodField实现了这个,但它似乎不是最好的解决方案:
class TourSerializer(serializers.ModelSerializer):
"""
Returns a list of tour objects.
"""
orders = serializers.SerializerMethodField()
class Meta:
model = Tour
fields = (
'id', 'orders'
)
def get_orders(self, obj):
orders = Order.objects.visible_for_me(self.context['request'].user).filter(tour=obj)
serializer = OrderSerializer(orders, many=True)
return serializer.data
答案 0 :(得分:1)
您可以覆盖序列化程序的__init__()
方法:
class YourModelSerializer(serializers.ModelSerializer):
.....
.....
def __init__(self, *args, **kwargs):
super(YourModelSerializer, self).__init__(*args, **kwargs)
user = self.context['request'].user
# Limit according to your need, whatever.
self.fields['field_name'].queryset = Model.objects.filter(user=user)