尝试简单的 Django 序列化器。我使用具有特定值的
queryset
然后我将
queryset
或
queryset.values()
传递给序列化器。为什么会出现500错误?
@csrf_protect
def geoLookup(request, **kwargs):
country = kwargs.get('Country')
city = kwargs.get('Place')
queryset = GeoNames_location.objects.filter(geoCountry_code=country, feature_class='P', geoAsciiName__istartswith=city).values_list("geoAsciiName", "geoLongitude", "geoLatitude", "geo_timezone", "geo_population", "geoCountry_code").order_by('-geo_population')[:5]
data = serializers.serialize("json", queryset.values()) # tried queryset and queryset.values()
parsed_data = json.loads(data)
pretty_json = json.dumps(parsed_data, indent=4)
return JsonResponse(json.loads(pretty_json), safe=False)
[24/Jul/2024 06:07:52] "GET /edit_chart_form HTTP/1.1" 200 18929
Internal Server Error: /geolookup/US/p
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper
result = _process_exception(request, e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper
response = view_func(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "G:\My Drive\myProgram\runtime\devui\ui\views.py", line 81, in geoLookup
data = serializers.serialize("json", queryset.values())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\serializers\__init__.py", line 134, in serialize
s.serialize(queryset, **options)
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\serializers\base.py", line 113, in serialize
concrete_model = obj._meta.concrete_model
^^^^^^^^^
AttributeError: 'dict' object has no attribute '_meta'
[24/Jul/2024 06:07:55] "GET /geolookup/US/p HTTP/1.1" 500 105779
出现的错误是因为你尝试将 Django 序列化器用于列表字典,而 Django 序列化器是为 Django 模型实例设计的。
queryset.values()
返回一个列表字典,而不是 Django 模型实例的查询集。
以下是如何解决此问题的几种方法:
1. 使用
values
方法返回数据:
你不需要使用
serializers.serialize
。
values
方法已经为你提供了一个字典列表,你可以直接将其传递给
JsonResponse
:
```python from django.http import JsonResponse
@csrf_protect def geoLookup(request, **kwargs): country = kwargs.get('Country') city = kwargs.get('Place') queryset = GeoNames_location.objects.filter( geoCountry_code=country, feature_class='P', geoAsciiName__istartswith=city ).values( "geoAsciiName", "geoLongitude", "geoLatitude", "geo_timezone", "geo_population", "geoCountry_code" ).order_by('-geo_population')[:5] return JsonResponse(list(queryset), safe=False) ```
2. 使用 Django REST framework:
如果你需要对序列化数据进行更多控制,或者计划构建 API,Django REST framework 是一个很好的选择。它提供了序列化器,可以轻松地将 Django 模型转换为 JSON。
```python from rest_framework import serializers from rest_framework.decorators import api_view from rest_framework.response import Response
from myapp.models import GeoNames_location
class GeoLocationSerializer(serializers.ModelSerializer): class Meta: model = GeoNames_location fields = ["geoAsciiName", "geoLongitude", "geoLatitude", "geo_timezone", "geo_population", "geoCountry_code"]
@api_view(['GET']) def geoLookup(request, **kwargs): country = kwargs.get('Country') city = kwargs.get('Place') queryset = GeoNames_location.objects.filter( geoCountry_code=country, feature_class='P', geoAsciiName__istartswith=city ).order_by('-geo_population')[:5] serializer = GeoLocationSerializer(queryset, many=True) return Response(serializer.data) ```
请注意,使用 Django REST framework 需要安装它 (
pip install djangorestframework
) 并将其添加到你的
INSTALLED_APPS
设置中。
这些方法都将返回你想要的 JSON 数据。选择最适合你需求和项目结构的方法。
标签:python,json,django,django-serializer From: 78786054