Prometheus
Prometheus

Reputation: 33625

How to create a mixin pattern in Python

I'm trying to understand the concept of mixins using the following example:

I have a simple serializer using the DRF:

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test
        fields = ('url', 'name', 'user')

I would like to create a mixin which enhances (overwrites the class get_queryset) for any custom serializer by added a check that the user owns the objects and only shows these items for example...

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)

So my TestSerializer would look like this:

class TestSerializer(serializers.ModelSerializer, UserListMixin):
    etc

and 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)

What I'm having difficulty with is creating the UserListMixin class. How can I return the correct object based on what I'm extending return [OBJECT].objects.filter(user=user) and would this approach work?

Upvotes: 1

Views: 1493

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599628

Filters are chainable, so the best thing to do here is to call the super method to get the default queryset, then add your filter on top:

def get_queryset(self, *args, **kwargs)
    user = self.request.user
    return super(UserListMixin, self).get_queryset(*args, **kwargs).filter(user=user)

Upvotes: 2

Related Questions