如何解决Django 模型:使用 OneToOneField 访问相关对象中的父对象属性
我正在尝试从与 OneToOneField 相关的 Profile 对象访问 Django User 对象的 username 属性。
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
username = models.TextField(default=user.username,primary_key=True)
image = models.ImageField(upload_to='images/profile')
header = models.CharField(max_length=64)
slug = AutoSlugField(populate_from='x')
bio = models.CharField(max_length=300,blank=True)
这样做的目的是能够使用 ReactJS 前端通过将登录时提供的用户名传递回 Django API 中的配置文件详细信息端点来获取 Profile 对象,其中用户名是端点的主键。
path('<pk>/profile/',ShowProfilePageView.as_view(),name='show_profile_page'),
对于传递给 Profile username 属性的默认参数,我已经尝试了许多不同的方法,但到目前为止没有任何效果。这甚至可能吗?
附录 1:ShowProfilePageView 视图
class ShowProfilePageView(generics.RetrieveUpdateDestroyAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
model = Profile
解决方法
要访问一对一字段的属性,您可以这样做:
profile = Profile.objects.get(pk='profile_pk') # an object of profile
username = profile.user.username
通过用户名搜索个人资料:
profile = Profile.objects.get(user=User.objects.get(username='username'))
因此,您不需要在 username
类上定义 Profile
字段
我认为您可以简单地覆盖视图中的 lookup_field
,如下所示:
class ShowProfilePageView(generics.RetrieveUpdateDestroyAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
model = Profile
lookup_field='user__username'
lookup_url_kwarg='username'
并像这样更新网址:
path('<str:username>/profile/',ShowProfilePageView.as_view(),name='show_profile_page')
因为通过 lookup_field
,视图将从 Profile 模型中查找 User 模型中的值。而 lookup_url_kwargs
是映射它应该从 url 使用的值。在 documentation 中可以找到更多信息。 仅供参考您应该从 Profile 模型中删除 username
字段,它应该使用 AutoField
(这是模型中主键的默认字段)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。