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.

classUserFilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
    defget_queryset(self):
        request = self.context.get('request', None)
        queryset = super(UserFilteredPrimaryKeyRelatedField, self).get_queryset()
        ifnot request ornot queryset:
            returnNonereturn 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:

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

    classMeta:
        model = models.Todofields= ('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?"