【问题标题】:RetrieveAPIView without lookup field?RetrieveAPIView 没有查找字段?
【发布时间】:2018-03-10 04:34:00
【问题描述】:

默认情况下,RetrieveAPIView 或 RetrieveUpdateAPIView 需要lookup_field 来检索模型。

但是,就我而言,我想通过 self.request.user 检索我的模型。

这里是views.py的例子

class ProfileRetrieveAndUpdateProfile(generics.RetrieveUpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileRetrieveAndUpdateSerializer
    lookup_field = 'user_id'

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

我可以使用 RetrieveAPIView 不带lookup_field吗?

【问题讨论】:

  • 您在哪里发现lookup_field 是必需的?我在文档中没有找到它,它在我的项目中起作用。
  • 此属性在GenericAPIView 中有默认值,用于获取对象。
  • 如果我不指定 lookup_field 会收到此错误:预期视图 ProfilePageView 将使用名为“pk”的 URL 关键字参数调用。修复您的 URL 配置,或正确设置视图上的 .lookup_field 属性。
  • 这意味着您只需要使用pk 某些/profile/213/ 访问网址
  • 是的。但我不想放额外的参数。 /profile/.. 也许不可能?

标签: django django-rest-framework django-views


【解决方案1】:

你需要覆盖get_object

def get_object(self):
  queryset = self.get_queryset()
  obj = get_object_or_404(queryset, user=self.request.user)
  return obj
猜你喜欢
  • 2017-11-25
  • 2014-11-12
  • 2011-08-08
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 2016-08-30
相关资源
最近更新 更多