Skip to content Skip to sidebar Skip to footer

How Can I Filter A ManyToManyField Against The Current User In The Browsable API In DRF?

I have 2 models, Todo and a Tag. Todo has a ManyToMany relationship with Tag. When adding new Todos from the Browsable API, I want to be able to see only the Tags added by the curr

Solution 1:

In your TodoCreateSerializer you need to add PrimaryKeyRelatedField with a custom queryset that has the filtered tags of a user.

First, you will need to create a custom PrimaryKeyRelatedField that filter any objects to get only those who owned by the user.

class UserFilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        request = self.context.get('request', None)
        queryset = super(UserFilteredPrimaryKeyRelatedField, self).get_queryset()
        if not request or not queryset:
            return None
        return queryset.filter(user=request.user)

(This is a generic one and can be used when filtering in objects by user)

Then you should use this one in you TodoCreateSerializer:

class TodoCreateSerializer(serializers.ModelSerializer): 
    tags = UserFilteredPrimaryKeyRelatedField(queryset= Tag.objects, many=True)

    class Meta:
        model = models.Todo
        fields = ('title', 'description', 'due_at', 'tags')

Post a Comment for "How Can I Filter A ManyToManyField Against The Current User In The Browsable API In DRF?"