未在Django REST框架中获取更新记录的记录列表。 [英] List of records not fetching updated records in Django REST framework..?

查看:94
本文介绍了未在Django REST框架中获取更新记录的记录列表。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django REST Framework API中,直到API重新启动或python文件(例如模型,序列化器或视图)中的任何代码更改之后,数据库表记录的列表才会更新。我已经尝试了事务提交,但是没有成功。以下是我的观点:

In Django REST Framework API, list of database table records are not getting updated until the API restart or any code change in python files like model, serializer or view. I've tried the transaction commit but it didn't worked. Below is my view :

class ServiceViewSet(viewsets.ModelViewSet):
    #authentication_classes = APIAuthentication,
    queryset = Service.objects.all()
    serializer_class = ServiceSerializer
    def get_queryset(self):
        queryset = self.queryset
        parent_id = self.request.QUERY_PARAMS.get('parent_id', None)
        if parent_id is not None:
           queryset = queryset.filter(parent_id=parent_id)
        return queryset   
    # Make Service readable only
    def update(self, request, *args, **kwargs): 
        return Response(status=status.HTTP_400_BAD_REQUEST)    
    def destroy(self, request, *args, **kwargs):
        return Response(status=status.HTTP_400_BAD_REQUEST)

序列化器如下所示:

class ServiceSerializer(serializers.ModelSerializer): 

    class Meta:
        model = Service
        fields = ('id', 'category_name', 'parent_id')
        read_only_fields = ('category_name', 'parent_id')

,模型看起来像这样:

class Service(models.Model):
    class Meta:
        db_table = 'service_category'
        app_label = 'api'
    category_name = models.CharField(max_length=100)
    parent_id = models.IntegerField(default=0)
    def __unicode__(self): 
        return  '{"id":%d,"category_name":"%s"}' %(self.id,self.category_name)

仅此服务会出现此问题,其余API均能正常工作。任何帮助将不胜感激。

This problem is occuring only with this service, rest of the APIs working perfectly fine. Any help will be appreciated.

推荐答案

因为要在 self.queryset上设置查询集是一个类属性,正在缓存中。这就是为什么您没有为每个请求获取更新的查询集的原因,这也是为什么Django REST Framework 在默认 get_queryset <的查询集上调用 .all() 。通过在查询集上调用 .all(),它将不再使用缓存的结果,并将强制执行新的评估,这就是您要寻找的。

Because you are setting up the queryset on self.queryset, which is a class attribute, it is being cached. This is why you are not getting an updated queryset for each request, and it's also why Django REST Framework calls .all() on querysets in the default get_queryset. By calling .all() on the queryset, it will no longer use the cached results and will force a new evaluation, which is what you are looking for.

class ServiceViewSet(viewsets.ModelViewSet):
    queryset = Service.objects.all()

    def get_queryset(self):
        queryset = self.queryset.all()
        parent_id = self.request.QUERY_PARAMS.get('parent_id', None)

        if parent_id is not None:
           queryset = queryset.filter(parent_id=parent_id)

        return queryset

这篇关于未在Django REST框架中获取更新记录的记录列表。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆