动态限制相关领域的查询 [英] Dynamically limiting queryset of related field

查看:112
本文介绍了动态限制相关领域的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Django REST框架,我想限制在创建的相关字段中可以使用哪些值。



例如考虑这个例子(基于过滤 http://django-rest-framework.org/api-guide/filtering.html,但更改为ListCreateAPIView):

  class PurchaseList(generics.ListCreateAPIView)
model = Purchase
serializer_class = PurchaseSerializer

def get_queryset(self):
user = self.request.user
return Purchase.objects.filter(buyer = user)

在此示例中,如何确保在创建时购买者可能只等于self.request.user,而这是在可浏览的API渲染器中,窗体中的下拉列表中填充的唯一值?

我最终做了类似于a href =https:// grou ps.google.com/forum/?fromgroups=#!searchin/django-rest-framework/filter/django-rest-framework/m3pYCyTbQ3o/Sj-TmD6p62QJ\">这里建议的这个。基本上我修改了我的序列化程序来窥探请求,哪种气味错了,但它完成了工作...这是它的外观(例如购买示例):



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) .get_fields(* args,** kwargs)
fields ['purchaseer']。queryset = allowed_objects(self.context ['view']。request.user,fields ['buyer'] .queryset)
返回字段

class Meta:
model = Purchase

allowed_objects是一个接收用户和查询的函数,并返回一个仅包含用户有权限链接的对象的过滤查询。这似乎适用于验证和可浏览的API下拉字段。


Using Django REST Framework, I want to limit which values can be used in a related field in a creation.

For example consider this example (based on the filtering example on http://django-rest-framework.org/api-guide/filtering.html , but changed to ListCreateAPIView):

class PurchaseList(generics.ListCreateAPIView)
    model = Purchase
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)

In this example, how do I ensure that on creation the purchaser may only be equal to self.request.user, and that this is the only value populated in the dropdown in the form in the browsable API renderer?

解决方案

I ended up doing something similar to what Khamaileon suggested here. Basically I modified my serializer to peek into the request, which kind of smells wrong, but it gets the job done... Here's how it looks (examplified with the purchase-example):

class PurchaseSerializer(serializers.HyperlinkedModelSerializer):
    def get_fields(self, *args, **kwargs):
        fields = super(PurchaseSerializer, self).get_fields(*args, **kwargs)
        fields['purchaser'].queryset = permitted_objects(self.context['view'].request.user, fields['purchaser'].queryset)
        return fields

    class Meta:
        model = Purchase

permitted_objects is a function which takes a user and a query, and returns a filtered query which only contains objects that the user has permission to link to. This seems to work both for validation and for the browsable API dropdown fields.

这篇关于动态限制相关领域的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆