Multiple lookup_fields for django rest framework

后端 未结 8 557
你的背包
你的背包 2020-12-10 03:30

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

/api/organization/10

I have a frontend consuming tho

8条回答
  •  自闭症患者
    2020-12-10 04:11

    Try this

    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)
    

    Then in View

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

    Hope this helps.

提交回复
热议问题