Django Rest框架的多个lookup_fields [英] Multiple lookup_fields for django rest framework

查看:513
本文介绍了Django Rest框架的多个lookup_fields的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个使用 id 作为查询字段的API,

I have multiple API which historically work using id as the lookup field:

/api/organization/10

我有一个前端在使用这些api。

I have a frontend consuming those api.

我正在建立一个新的界面,由于某些原因,我想使用一个插件来代替id:

I'm building a new interface and for some reasons, I would like to use a slug instead an id:

/api/organization/my-orga

API已构建使用Django Rest Framework。除了查找字段的更改外,api行为应保持不变。

The API is built with Django Rest Framework. Except the change of lookup field, the api behavior should stay the same.

是否有一种解决方案,允许我的API与 slug一起使用 pk 吗?这两个路径应该给他们相同的结果:

Is there a solution to allow my API to work with both a slug and a pk ? Those two path should give them same results:

/api/organization/10
/api/organization/my-orga

这是我的API定义:

# urls.py
router = DefaultRouter()
router.register(r'organization', Organization)
urlpatterns = router.urls

#view.py
class Organization(viewsets.ModelViewSet):
    queryset = OrganisationGroup.objects.all()
    serializer_class = OrganizationSerializer

# serializer.py
class OrganizationSerializer(PermissionsSerializer):
    class Meta:
        model = Organization

感谢您的帮助。

推荐答案

尝试一下

from django.db.models import Q
import operator
class MultipleFieldLookupMixin(object):
    def get_object(self):
        queryset = self.get_queryset()             # Get the base queryset
        queryset = self.filter_queryset(queryset)  # Apply any filter backends
        filter = {}
        for field in self.lookup_fields:
            filter[field] = self.kwargs[field]
        q = reduce(operator.or_, (Q(x) for x in filter.items()))
        return get_object_or_404(queryset, q)

然后在视图中

class Organization(MultipleFieldLookupMixin, viewsets.ModelViewSet):
    queryset = OrganisationGroup.objects.all()
    serializer_class = OrganizationSerializer
    lookup_fields = ('pk', 'another field')

希望这会有所帮助。

这篇关于Django Rest框架的多个lookup_fields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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