Jimmar
Jimmar

Reputation: 4459

Django Rest Framework serializer check if exists in related Many to Many fiield

I have a custom User model with a blocked field as

class User(AbstractUser):
    username = None
    email = models.EmailField(_('email address'), unique=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    blocked = models.ManyToManyField("User", related_name="blocked_by", blank=True)

and I'm trying to have a serializer where I can look up a user by their ID and find out if they are blocked or not by the logged in user

my current is serializer

class UserSerializer(serializers.ModelSerializer):
    is_blocked = serializers.BooleanField() # need to populate this

    class Meta:
        model = User
        fields = ['id', 'email', 'user_type', 'is_blocked']

and my view

class UserDetail(generics.RetrieveAPIView):
    authentication_classes = (authentication.JWTAuthentication,)
    permission_classes = (permissions.IsAuthenticated,)

    serializer_class = UserSerializer
    queryset = User.objects.all()

I'm just not sure how to populate that value such that it'd be true if the inquiried user is in the blocked manyToMany field of the logged in user or not

Upvotes: 0

Views: 1286

Answers (1)

gdef_
gdef_

Reputation: 1936

You can use SerializerMethodField and calculate it. Get the authenticated user and check if the serialized user is in the blocked list.

class UserSerializer(serializers.ModelSerializer):
    is_blocked = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id', 'email', 'user_type', 'is_blocked']

    def get_is_blocked(self, obj):
        # you might need to do some fixes in this method, I'm not 100% sure that it works like you want
        logged_in_user = self.context['request'].user  # the authenticated user
        is_blocked = logged_in_user.blocked.filter(id=obj.id).exists()  # check if the serialized user (obj) is in the auth user blocked list
        return is_blocked

Upvotes: 2

Related Questions