【问题标题】:want to filter model objects by email, however filtering is not working in Django REST api想要通过电子邮件过滤模型对象,但是过滤在 Django REST api 中不起作用
【发布时间】:2021-08-13 17:17:08
【问题描述】:

我在 Django REST 框架中有我的 API:

这是我的models.py:

class myModel(models.Model):
    user_email = models.CharField(max_length= 200, null= False)

这是我的views.py:

class GetItemsByEmail(generics.ListAPIView):
   def get_queryset(self):
       email_items = self.request.query_params.get("user_email")
       if(email_items is not None):
          itemsReturned =  myModel.objects.all().filter(user_email = email_items)
          return Response(data= itemsReturned)

这是我的 urls.py:

url_patterns = [
   path('users/account=<str:id>/items', GetItemsByEmail.as_view()),
   ]

我的问题:

我得到一个空列表,从对上述端点进行 API 调用一无所获。 我想获取与特定电子邮件关联的数据库中的所有项目,但过滤器不起作用? 这背后的原因是什么?

【问题讨论】:

  • 在django模型上根据条件过滤,需要使用下面的形式myModel.objects.filter(user_email = email_items)过滤时不要使用.all()

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


【解决方案1】:

您在 URL 中定义了参数,因此这是一个 URL 参数。但是request.query_params 不是由路径决定的,而是由query string [wiki] 决定的。

你通过self.kwargs获取URL参数,所以:

class GetItemsByEmail(generics.ListAPIView):
    
    def get_queryset(self):
        #    use self.kwargs &downarrow;
        email_items = self.kwargs.get('user_email')
        if email_items is not None:
            return myModel.objects.filter(user_email=email_items)
        else:
            # return some queryset
            pass

您的urls.py 应该更新为与user_email 一起使用,而不是id

url_patterns = [
   path('users/account=<str:user_email>/items', GetItemsByEmail.as_view()),
]

虽然并非不可能,但在 URL 中使用等号或包含电子邮件地址并不常见,这些通常通过查询字符串或在负载中的非 GET 请求的情况下完成请求或标头。

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2018-10-05
    • 2013-03-16
    • 1970-01-01
    相关资源
    最近更新 更多