django不使用序列化器來進行查詢結果序列化

斬·侯發表於2020-10-27

models:

	from django.db import models

	class User(models.Model):
	    name = models.CharField(max_length=25)
	    age = models.CharField(max_length=5)
	    sex = models.CharField(max_length=10)

    class Meta:
        db_table = 'tb_user'

app01.urls:

	from django.urls import path
	from .views import *
	
	urlpatterns = [
	    path('index/', Index.as_view()),
	    path('index2/', Index2.as_view()),
	]

主路由:

	from django.contrib import admin
	from django.urls import path, include
	
	urlpatterns = [
	    path('admin/', admin.site.urls),
	    path('app01/', include('apps.app01.urls')),
	    path('app02/', include('apps.app02.urls')),
	]

views:

	from django.http import JsonResponse
	from django.shortcuts import render, HttpResponse
	from rest_framework.views import APIView
	from rest_framework.response import Response
	from .serializers import UserSER
	from django.views import View
	
	class Index(View):
    	def get(self,request):
        user = User.objects.all()
        list = []
        for i in user:
            data = {
                'name': i.name,
                'age': i.age,
                'sex': i.sex
            }
            list.append(data)
        print(list)

    data = request.GET.get('name')
    return JsonResponse({'data':list})

	class Index2(APIView):
    def get(self,request):
        data = request.query_params
        return Response(data)

相關文章