简体   繁体   English

在 Django REST 框架中使用 lookup_field 中的相关字段

[英]Use a related field in lookup_field in Django REST framework

I have a user model and a profile model that is created automatically when a user is registered.我有一个用户 model 和一个用户注册时自动创建的配置文件 model。 In my view for retrieving the user profile, I am trying to get the user profile using the username but DRF uses pk by default.在我检索用户配置文件的视图中,我试图使用username获取用户配置文件,但 DRF 默认使用pk So I added a lookup field with the username but DRF can't seem to resolve it:所以我添加了一个带有username的查找字段,但 DRF 似乎无法解决它:

my profile model:我的profile model:

class Profile(TimeStampedModel):
    user = models.OneToOneField('User', on_delete=models.CASCADE, related_name='customer_profile')
    bio = models.TextField(blank=True)
    image = models.URLField(blank=True)
    
    def __str__(self):
        return self.user.username

my profile serializer :我的profile serializer

class ProfileSerializer(serializers.ModelSerializer):
    username = serializers.StringRelatedField(source='user.username', read_only=True)
    bio = serializers.CharField(allow_blank=True, allow_null=True)
    image = serializers.SerializerMethodField()
    
    class Meta:
        model = Profile
        fields = ['username', 'bio', 'image']
        
    def get_image(self, obj):
        if obj.image:
            return obj.image
        
        return 'https://static.productionready.io/images/smiley-cyrus.jpg'

my profile retrieving view :我的profile retrieving view

class ProfileRetrieveAPIView(generics.RetrieveAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'username'


    def retrive(self, request, username, *args, **kwargs):
        
        try:
            profile = Profile.objects.select_related('user').get(
                user__username = username
            )
        except Profile.DoesNotExist:
            ProfileDoesNotExist
        
        serializer = self.serializer_class(profile)
        
        return Response(serializer.data, status=status.HTTP_200_OK)

my profile endpoint:我的个人资料端点:

urlpatterns = [ 
    # ....
    path('profiles/<str:username>', views.ProfileRetrieveAPIView.as_view()),
]

I am getting the error:我收到错误消息:

Cannot resolve keyword 'username' into field. Choices are: bio, created_at, id, image, updated_at, user, user_id

What am I doing wrong?我究竟做错了什么?

Use nested serialzer.使用嵌套序列化器。

class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ('username',)

And in your profile serializer:在您的个人资料序列化程序中:

  username = UserSerializer(many=False, read_only=True)

You can use this你可以用这个

class ProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username', read_only=True)
    bio = serializers.CharField(allow_blank=True, allow_null=True)
    image = serializers.SerializerMethodField()
    
    class Meta:
        model = Profile
        fields = ['username', 'bio', 'image']
        
    def get_image(self, obj):
        if obj.image:
            return obj.image
        
        return 'https://static.productionready.io/images/smiley-cyrus.jpg'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM