【问题标题】:Django Rest Framework serializer check if exists in related Many to Many fiieldDjango Rest Framework序列化程序检查相关多对多字段中是否存在
【发布时间】:2021-06-11 20:46:06
【问题描述】:

我有一个带有blocked 字段的自定义用户模型

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)

我正在尝试使用一个序列化程序,我可以在其中通过用户 ID 查找用户,并了解他们是否被登录用户阻止

我目前是序列化器

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

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

我的看法

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

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

我只是不确定如何填充该值,以便查询的用户是否在登录用户的blocked manyToMany 字段中

【问题讨论】:

    标签: django django-models django-rest-framework django-serializer


    【解决方案1】:

    您可以使用SerializerMethodField 并计算它。获取认证用户,检查序列化用户是否在屏蔽列表中。

    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
    

    【讨论】:

    • 非常感谢!我完全忘记了SerializerMethodField
    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 2016-01-19
    • 2015-03-27
    • 2015-10-02
    • 1970-01-01
    相关资源
    最近更新 更多