如何在django中序列化一个 Dataframe ?有没有办法在django中返回 Dataframe 沿着查询集?

kcugc4gi  于 2023-01-14  发布在  Go
关注(0)|答案(2)|浏览(172)

我在这里尝试做的是根据用户的选择(如日期、组和符号)获取查询。
我想用django_pandas把这个查询集转换成一个 Dataframe 。
我尝试将生成的 Dataframe 转换为JSON对象,但它给出了一些错误,如:
TypeError:"DataFrame"类型的对象不可JSON序列化
我的视图集如下所示:

class StockPriceDataViewSet(mixins.ListModelMixin,
                     viewsets.GenericViewSet):
    queryset = StockPriceData.objects.all()
    serializer_class = StockPriceDataSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_fields = {
        'date':['gte','lte'],
        'org__symbol':['exact'],
        'org__group':['exact'],
    }
    permission_classes = (AllowAny,)
    
    @action(methods=['GET'], detail=False, url_path='stock')
    def get_df(self, request):
        queryset = self.queryset
        result = generate_df(queryset=queryset)
        return Response(result, status=status.HTTP_200_OK)
def generate_df(queryset):
    df = queryset.to_dataframe()
    df = df.drop(['s_n','id'], axis=1)
    # df = df.set_index(['org','date'])
    result = df.to_json(orient='records', date_unit='ms', 
    lines=True).splitlines()
    return result

当我在交互式环境中运行上面的代码时,它运行得很顺利,没有任何错误,但是当Django处理请求时,一个错误弹出:'NoneType' object has no attribute 'to_json'
还有,JSON的格式并不像我期望的那样标准。我在这里做错了什么?有人能解释一下吗?任何帮助都将不胜感激。
EDIT2:删除了get_queryset()方法,因为它在此处不执行任何操作。添加了@action方法以检索 Dataframe 。
这里还有另一个问题,返回的JSON对象不是我最初提供给函数的查询集。过滤器集字段没有像它们应该的那样工作。每次我试图获取特定的数据框时,返回的是整个数据库的数据框,而不是特定的查询。最简单的解决方案是什么?
编辑:添加堆栈跟踪:

AttributeError at /api/v1/stock/price/
'tuple' object has no attribute 'model'

Request Method: GET
Request URL: http://localhost:8000/api/v1/stock/price/?page=1
Django Version: 3.0
Python Executable: /home/anjaan/project/fintech/venv/bin/python
Python Version: 3.8.5
Python Path: ['/home/anjaan/project/fintech', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/anjaan/project/fintech/venv/lib/python3.8/site-packages']
Server time: Wed, 17 Feb 2021 05:49:42 +0000
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'drf_yasg',
 'rest_framework',
 'rest_framework.authtoken',
 'rest_framework_swagger',
 'rest_framework_jwt',
 'rest_auth',
 'allauth',
 'allauth.account',
 'django_extensions',
 'django_rest_passwordreset',
 'django_filters',
 'channels',
 'users',
 'misc',
 'notification',
 'finance']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'fintech.middleware.UserAgentMiddleware',
 'fintech.middleware.UserActivityLogMiddleware']

Traceback (most recent call last):
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 38, in list
    queryset = self.filter_queryset(self.get_queryset())
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 150, in filter_queryset
    queryset = backend().filter_queryset(self.request, queryset, self)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django_filters/rest_framework/backends.py", line 90, in filter_queryset
    filterset = self.get_filterset(request, queryset, view)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django_filters/rest_framework/backends.py", line 31, in get_filterset
    filterset_class = self.get_filterset_class(view, queryset)
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django_filters/rest_framework/backends.py", line 73, in get_filterset_class
    class AutoFilterSet(self.filterset_base):
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django_filters/rest_framework/backends.py", line 74, in AutoFilterSet
    class Meta(MetaBase):
  File "/home/anjaan/project/fintech/venv/lib/python3.8/site-packages/django_filters/rest_framework/backends.py", line 75, in Meta
    model = queryset.model

Exception Type: AttributeError at /api/v1/stock/price/
Exception Value: 'tuple' object has no attribute 'model'
brccelvz

brccelvz1#

你写道:

df = df.set_index(['org','id'],inplace=True)

inplace=True意味着您要对同一对象进行更改,因此该方法不会返回任何导致None存储在df中的内容。将该行更改为以下任一行:

df.set_index(['org','id'], inplace=True)

df = df.set_index(['org','id'])
lndjwyie

lndjwyie2#

你可以使用Django REST Pandas.这里是文档https://pypi.org/project/rest-pandas/

相关问题