Django Rest Framework slug_field 错误

Django Rest Framework slug_field error

我有这个序列化器和模型。我想在我的 API 中显示 User 模型的 username 字段,但我收到此错误。

AttributeError at /api/v1/client_share_requests/1/

'Profile' object has no attribute 'username'

serializers.py

class ClientShareRequestSerializer(serializers.ModelSerializer):

    checked_by = serializers.SlugRelatedField(
        many=True,
        queryset=Profile.objects.all(),
        slug_field='username'
    )

    class Meta:
        model = ClientShareRequest
        fields = ('checked_by')

models.py

  class Profile(models.Model):
        user = models.OneToOneField(User, related_name='profile')

  class ClientShareRequest(models.Model):
        checked_by = models.ManyToManyField(Profile, blank=True,
                                            related_name='checked_by')

我尝试像这样访问用户模型实例:

   checked_by = serializers.SlugRelatedField(
        many=True,
        queryset=Profile.objects.all(),
        slug_field='user.username'
   )

但我收到此错误:

'Profile' object has no attribute 'user.username'

感谢您的帮助。 (对不起我的英语:P)

我的猜测是 DRF 不允许在 SlugRelatedFields 上进行嵌套属性查找。简单的解决方法是在 Profile 模型上添加用户名 属性 并在序列化程序中使用它:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')

    @property
    def username(self): 
        return self.user.username

class ClientShareRequest(models.Model):
    checked_by = models.ManyToManyField(Profile, blank=True,
                                            related_name='checked_by')


class ClientShareRequestSerializer(serializers.ModelSerializer):

    checked_by = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='username'
    )

    class Meta:
        model = ClientShareRequest
        fields = ('checked_by', )

这适用于读取:)