django - 我可以在没有 'RetrieveUpdateAPIView' 字段的情况下使用 'look_up' 吗?

标签 django http django-rest-framework django-views

RetrieveUpdateAPIView 的 url 适用于特定字段。 (例如 /profile/update/<pk>)

我从 HTTP header 中的 token 获取用户帐户,因此很难将用户的 pk 包含到 url 中。

这个 View 是我的 RetrieveUpdateAPIView。

class ProfileRetrieveAndUpdateProfile(generics.RetrieveUpdateAPIView):
    serializer_class = ProfileRetrieveAndUpdateSerializer
    # lookup_field = 'pk'

    def get_queryset(self):
        qs = Profile.objects.all()
        logged_in_user_profile = qs.filter(user=self.request.user)
        return logged_in_user_profile

我应该只使用 views.APIView 来实现这个功能吗?

最佳答案

我通过覆盖 get_object 解决了这个问题。

def get_object(self):
  queryset = self.get_queryset()
  obj = get_object_or_404(queryset, user=self.request.user)
  return obj

干杯

关于django - 我可以在没有 'RetrieveUpdateAPIView' 字段的情况下使用 'look_up' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46119746/

相关文章:

python - 在 Celery/Django : cannot find reference 'control' in celery. 任务.control

java - 异常的 Http 状态代码

移动安全 + Stripe token ?它们如何安全?

ios - 在 iPad 或 iPhone 上无需 UI 发送电子邮件的替代方法

python - 如何在 django 模型的字段中保存单个空格 ("")?

Django REST 测试 - 如何指定引用在 setUp 函数中创建的模型实例的 pk 参数

django - 在 Django 模板中格式化 TimeField 不显示任何内容

python - 'getattr() : attribute name must be string' error in admin panel for a model with an ImageField

python - 使用 Django 继承区分父模型的子模型

python - Django休息框架: get all data in relation