gpt4 book ai didi

python - 字段名称 user_username 对于模型配置文件无效

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:09 25 4
gpt4 key购买 nike

错误名称:字段名称user_username对于模型配置文件无效

我正在构建我的编辑个人资料 View 。

这是我的views.py

class ProfileEditAPIView(DestroyModelMixin, UpdateModelMixin, generics.RetrieveAPIView):
serializer_class = ProfileEditSerializer

def get_queryset(self):
logged_in_user = User.objects.filter(username=self.request.user.username)
return logged_in_user

def get_object(self):
queryset = self.get_queryset()
obj = get_object_or_404(queryset)
return obj.profile

def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)

def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)

我可以正确获取 user_id,但不知何故我无法访问其用户名字段

这是serializers.py

class ProfileEditSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = (
'user_username', <<<
'title',
'gender',
'birth',
'height',
'height_in_ft',
'profile_img',
)

models.py

class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
title = models.TextField(max_length=155, blank=True)
gender = models.CharField(max_length=10, choices=GENDER_CHOICES, default='u') # Recommend Factor
location = models.CharField(max_length=40, choices=LOCATION_CHOICES, default='ud') # Recommend Factor
birth = models.DateField(default='1992-07-23', blank=True, null=True) # Recommend Factor
height = models.CharField(max_length=5, default='undefined')
height_in_ft = models.BooleanField(default=True)
profile_img = models.ImageField(
upload_to=upload_location,
null=True,
blank=True)

为什么我们无法访问用户的用户名?我们该如何解决这个问题?

谢谢

最佳答案

您可以使用这种方式从 User 模型获取用户名

class ProfileEditSerializer(serializers.ModelSerializer):
username = serializers.CharField(read_only=True, source="user.username")

class Meta:
model = Profile
fields = (
'username',
'title',
. . . .
)

关于python - 字段名称 user_username 对于模型配置文件无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46499573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com