在Django Rest Framework中过滤JSON记录 [英] Filter json records in Django Rest Framework
问题描述
我创建了一个DRF API端点,以便能够将一些数据捕获到数据库中并使用Jquery在Django页面上显示。
I created a DRF API endpoint in order to be able to grab some data to my database and show it on my Django page using Jquery.
我的示例数据看起来像这样:
My sample data looks like this:
{
"item": "Someitem",
"Price": 120,
"Status": "Free"
},
{
"item": "SecondItem,
"Price": 90,
"Status": "Taken"
},
因此,如果我从JQuery检索到此链接的端点: http://127.0.0.1:8000/tst/
,我将获取所有记录并将所有记录显示在我的网页中。例如,我只想检索仅其状态
字段设置为已捕获
的记录?有什么方法可以编辑DRF请求,使其指向 http://127.0.0.1:8000/tst/Taken
?或者,如果用户希望检索状态设置为免费
的所有其他内容,它将指向 http://127.0.0.1:8000/tst/Free
?我知道我可以用jquery做到这一点,但实际上我想在服务器端做到这一点。
So if i retrieve the endpoint from JQuery to this link: http://127.0.0.1:8000/tst/
, i'll get all the records and have all of them shown in my web page. But what if, for example, i only want to retrieve only the records whose Status
field is set to Taken
? Is there any way to edit the DRF request so that it points to http://127.0.0.1:8000/tst/Taken
? Or instead, if the user wants to retrieve all the others with the status set to Free
, it will point to http://127.0.0.1:8000/tst/Free
? I know i could do it with jquery, but i would actually like to do it server-side.
我尝试过这样做:
queryset = tst.objects.filter(Status="Taken")
但是这里的问题是,它将始终仅从我的数据库中仅记录接受
记录。就我而言,我想找到一种有时可以从模板中检索 Taken
的方法,而另一些时候可以检索 Free
的方法。
But the problem here, is that it will always take only the Taken
records from my DB. In my case, i want to find a way to retrieve Taken
sometimes, and Free
some other times from the template.
我是DRF的新手,所以我的设置非常简单:
I'm fairly new to DRF, so my setup is pretty basic:
视图。 py
class tstList(generics.ListCreateAPIView):
queryset = tst.objects.all()
serializer_class = tstSerializer
class tstDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = tst.objects.all()
serializer_class = tstSerializer
url.py
path('tst/', views.tstList.as_view()),
path('tst/<int:pk>/', views.tstDetail.as_view()),
models.py
class tst(models.Model):
item = models.CharField()
Price = models.FloatField()
Status = models.CharField()
def save(self, *args, using=None, **kwargs):
super(tst, self).save(*args, **kwargs)
推荐答案
看看 DRF文档。
您的情况下,建议您安装 django_filters
,然后在您看来:
Have a look on DRF doc.
In your case, I'd suggest you install django_filters
, then in your view:
from django_filters.rest_framework import DjangoFilterBackend
class tstList(generics.ListCreateAPIView):
queryset = tst.objects.all()
serializer_class = tstSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ('Status',)
这篇关于在Django Rest Framework中过滤JSON记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!