我正在尝试使用以下示例来理解mixins的概念:
我有一个使用DRF的简单序列化程序:
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = Test
fields = ('url', 'name', 'user')
我想创建一个mixin,它通过添加一个用户拥有对象的检查来增强(覆盖类get_queryset)任何自定义序列化程序,并且仅显示这些项目...
def get_queryset(self):
"""
This view should return a list of all the items
for the currently authenticated user.
"""
user = self.request.user
return ???????.objects.filter(user=user)
所以我的TestSerializer看起来像这样:
class TestSerializer(serializers.ModelSerializer, UserListMixin):
etc
和UserListMixin:
class UserListMixin(object):
"""
Filtering based on the value of request.user.
"""
def get_queryset(self, *args, **kwargs):
"""
This view should return a list of all the purchases
for the currently authenticated user.
"""
user = self.request.user
return super([?????????], self).get_queryset(*args, **kwargs).filter(user=user)
我遇到的困难是创建UserListMixin
课程。如何根据我正在扩展return [OBJECT].objects.filter(user=user)
的内容返回正确的对象?这种方法是否有效?
答案 0 :(得分:2)
过滤器是可链接的,因此最好的办法是调用super方法获取默认查询集,然后在顶部添加过滤器:
def get_queryset(self, *args, **kwargs)
user = self.request.user
return super(UserListMixin, self).get_queryset(*args, **kwargs).filter(user=user)