[英]DRF: How do you create multiple "detail" views for a model?
I have a django model that has multiple fields that need to be used as a key, and also has some detail views.我有一个 django model 有多个需要用作键的字段,并且还有一些详细视图。
For example, my endpoints currently look like this, using detail=True
to get the second set:例如,我的端点当前看起来像这样,使用detail=True
来获取第二组:
my.api/things/{id_1} (GET, POST, DELETE)
my.api/things/{id_1}/whatever (GET, POST)
That's all great, but I have to get to something that looks like this instead:这一切都很好,但我必须得到一些看起来像这样的东西:
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)
If it helps, the set of detail endpoints (ie. whatever
) is identical, and there's no difference in functionality between the two.如果有帮助,那么详细端点集(即, whatever
)是相同的,并且两者之间的功能没有区别。 I just need to be able to access the database through either field.我只需要能够通过任一字段访问数据库。
I'm new to django so I'm sorry if this is a simple question.我是 django 的新手,所以如果这是一个简单的问题,我很抱歉。 Any help would be appreciated!任何帮助,将不胜感激!
You can simply inherit base class and make whatever you want.您可以简单地继承基础 class 并制作您想要的任何东西。
For example,例如,
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
You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.然后,您可以在需要应用自定义行为的任何时候简单地将这个 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.