简体   繁体   中英

django-rest-framework : restrict RelatedField queryset according to request

I have a model with a ForeignKey

models.py

class B(models.Model):
    user = models.ForeignKey(contrib.auth.User)

class A(models.Model):
    b = models.ForeignKey(B)

serializers.py

class ASerializer(serializers.ModelSerializer):
    class Meta:
        model = A
        fields = ['b']

views.py

class AViewSet(iewsets.ModelViewSet):
    queryset = A.objects.all()
    serializer_class = ASerializer

Now what I want is to restrict the Ab values to the B instances owned by the currently logged-in user.

I know how to enforce that at saving-time, but I would like to only present the relevant queryset in the dropdown choice in the browsable API interface .

If one can define a queryset argument on the RelatedField , it's static and can't depend on the current request.

Any ideas ?

Well you could try overriding queryset in init of serializer. something like

def __init__(self, *args, **kwargs):
    super(MySerializerClass, self).__init__(*args, **kwargs)
    if self.context.get('request', None):
        field = self.fields.get('b')
        field.queryset = field.queryset.filter(user=request.user)

Current user shall be accessible through self.context.

You can modify the get_queryset:

class AViewSet(iewsets.ModelViewSet):
    serializer_class = ASerializer

    def get_queryset(self):
        user = self.request.user
        return A.objects.filter(b__user = user)

ref: http://www.django-rest-framework.org/api-guide/filtering/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM