[英]DRF: How do you create multiple "detail" views for a model?
我有一個 django model 有多個需要用作鍵的字段,並且還有一些詳細視圖。
例如,我的端點當前看起來像這樣,使用detail=True
來獲取第二組:
my.api/things/{id_1} (GET, POST, DELETE)
my.api/things/{id_1}/whatever (GET, POST)
這一切都很好,但我必須得到一些看起來像這樣的東西:
my.api/things/{id_1} (GET, POST, DELETE)
my.api/things/{id_1}/whatever (GET, POST)
my.api/things/other_id/{id_2} (GET, POST, DELETE)
my.api/things/other_id/{id_2}/whatever (GET, POST)
如果有幫助,那么詳細端點集(即, whatever
)是相同的,並且兩者之間的功能沒有區別。 我只需要能夠通過任一字段訪問數據庫。
我是 django 的新手,所以如果這是一個簡單的問題,我很抱歉。 任何幫助,將不勝感激!
您可以簡單地繼承基礎 class 並制作您想要的任何東西。
例如,
class MultipleFieldLookupMixin:
"""
Apply this mixin to any view or viewset to get multiple field filtering
based on a `lookup_fields` attribute, instead of the default single field filtering.
"""
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:
if self.kwargs[field]: # Ignore empty fields.
filter[field] = self.kwargs[field]
obj = get_object_or_404(queryset, **filter) # Lookup the object
self.check_object_permissions(self.request, obj)
return obj
然后,您可以在需要應用自定義行為的任何時候簡單地將這個 mixin 應用到視圖或視圖集。
class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_fields = ['account', 'username']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.