Django 模型:使用 OneToOneField 访问相关对象中的父对象属性

时间:2021-05-13 07:42:41

标签: reactjs django django-models django-rest-framework one-to-one

我正在尝试从与 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 对象,其中用户名是端点的主键。< /p>

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

2 个答案:

答案 0 :(得分:0)

要访问一对一字段的属性,您可以这样做:

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 字段

答案 1 :(得分:0)

我认为您可以简单地覆盖视图中的 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(这是模型中主键的默认字段)。

相关问题