标签:资源 query res 隐藏 字段名 bsp use imp integer
from django.db import models from django.conf import settings class User(models.Model): SEX_CHOICES = ((0, ‘男‘), (1, ‘女‘)) name = models.CharField(max_length=64, verbose_name=‘姓名‘) password = models.CharField(max_length=64) age = models.IntegerField() height = models.DecimalField(max_digits=5, decimal_places=2, default=0) sex = models.IntegerField(choices=SEX_CHOICES, default=0) # sex = models.CharField(choices=[(‘0‘, ‘男‘), (‘1‘, ‘女‘)]) icon = models.ImageField(upload_to=‘icon‘, default=‘icon/default.png‘) # 自定义序列化给前台的字段 # 优点:1)可以格式化数据库原有字段的数据 2)可以对外隐藏数据库字段名 3)可以直接连表操作 @property # 制造插头 def gender(self): return self.get_sex_display() @property def img(self): return settings.BASE_URL + settings.MEDIA_URL + self.icon.name def __str__(self): return self.name
from rest_framework import serializers from . import models class UserModelSerializer(serializers.ModelSerializer): class Meta: # 该序列化类是辅助于那个Model类的 model = models.User # 设置参与序列化与反序列化字段 # 插拔式:可以任意选择字段返回给前台(插头都是在Model类中制造) # fields = [‘name‘, ‘age‘, ‘height‘, ‘sex‘, ‘icon] fields = [‘name‘, ‘age‘, ‘height‘, ‘gender‘, ‘img‘]
from rest_framework.views import APIView from rest_framework.response import Response from . import models, serializers class UserAPIView(APIView): def get(self, request, *args, **kwargs): pk = kwargs.get(‘pk‘) if pk: # 单查 # 1)数据库交互拿到资源obj或资源objs # 2)数据序列化成可以返回给前台的json数据 # 3)将json数据返回给前台 obj = models.User.objects.get(pk=pk) serializer = serializers.UserModelSerializer(obj, many=False) return Response(serializer.data) else: # 群查 # 1)数据库交互拿到资源obj或资源objs # 2)数据序列化成可以返回给前台的json数据 # 3)将json数据返回给前台 queryset = models.User.objects.all() # many操作的数据是否是多个 serializer = serializers.UserModelSerializer(queryset, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): # 单增 # 1)从请求request中获得前台提交的数据 # 2)将数据转换成Model对象,并完成数据库入库操作 # 3)将入库成功的对象列化成可以返回给前台的json数据(请求与响应数据不对等:请求需要提交密码,响应一定不展示密码) # 4)将json数据返回给前台 return Response()
标签:资源 query res 隐藏 字段名 bsp use imp integer
原文地址:https://www.cnblogs.com/baohanblog/p/12327642.html