django (python) 使用 models serializers views key_words

给你一囗甜甜゛ 提交于 2020-01-01 13:13:47

1. models

from django.db import models


class Test(models.Model):
    id = models.BigAutoField(primary_key=True, max_length=20)
    name = models.CharField(max_length=255, null=False, blank=False)
    value = models.TextField(db_column='value',null=False, blank=False)
    
    def __str__(self):
        reutrn self.name
        
    class Meta:
        db_table = 'test' #数据库名


2. serializers

from rest_framework import serializers

class TestSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(read_only=True)
    value = serializers.CharField(read_only=True)

3. views

from .models import Test
from .serializers import TestSerializer
from rest_framework.viewsets import GenericViewSet
from rest_framework import status
from django.http import HttpResponse, JsonResponse
from rest_framework.response import Response



class TestViewSet(GenericViewSet):
    authentication_classes = (TokenAuthentication,)
    serializer_class = CfsTestSerializer
    queryset = CfsTest.objects.all()

    def get_test(self, request, *args, **kwargs):
        serializer = self.get_serializer(self.queryset)
        print('\n==================\n')
        print("data:")
        print(serializer.data)
        print("\n=================\n")

        t0 = time.clock()
        d = Test.objects.all()
        serializer = TestSerializer(data=d, many=True)
        serializer.is_valid()
        datas = serializer.data
        data = datas[0].get('value')
        t1 = time.clock()
        print("time:", t1-t0)

        return Response("end...")

4. key_words

关键字:

  1. db_column

  2. db_table

  3. null=True/False

  4. blank=True/False

  5. default='default'

  6. primary_key=True

  7. max_length=255

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!