标签:foreign 建模 false rom 信息 姓名 odi contex from
from rest_framework import serializers class TestSerializer(serializers.Serializer): name = serializers.CharField(max_length=20, required=True) code = serializers.CharField(max_length=20, required=True)
from django.http import HttpResponse, JsonResponse from django.contrib.auth import authenticate from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from school.serializers.school import TestSerializer class TestView(APIView): def get(self, request): # 获取auth中的用户 user = request.user if user.is_authenticated: # is_superuser return HttpResponse(user.username + ‘已授权‘) return HttpResponse(‘未授权‘) def post(self, request): serializer = TestSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data.get("name", "") password = serializer.validated_data.get("code", "") # 调用authenticate方法 user = authenticate(username=username, password=password) if user is not None: content = { "status": True, "message": "账户正确" } return JsonResponse(data=content, status=status.HTTP_200_OK) else: content = { "status": False, "message": "账号或者密码不正确" } return JsonResponse(data=content, status=status.HTTP_200_OK) else: return Response(data=serializer.errors)
from django.db import models class School(models.Model): name = models.CharField(max_length=32, verbose_name="名称") code = models.CharField(max_length=16, verbose_name="代码") location = models.CharField(max_length=128, verbose_name="地址") class Student(models.Model): name = models.CharField(max_length=32, verbose_name="姓名") age = models.IntegerField(verbose_name="年龄") school = models.ForeignKey(to=School,verbose_name="学校", on_delete=models.CASCADE)
# -*- coding: utf-8 -*- from rest_framework import serializers from school.models import Student, School class StudentSerializer(serializers.ModelSerializer): # 多对多时添加参数 many=True school = serializers.SlugRelatedField(read_only=False, slug_field="name", queryset=School.objects.all()) # address = serializers.CharField(source="school.address", default=None) def create(self, validated_data): # some actions instance = super().create(validated_data) return instance def update(self, instance, validated_data): user = self.context[‘request‘].user # 请求的用户 username = self.context[‘request‘].data.get(‘username‘) # 请求的参数username instance.name = validated_data[‘name‘] # 请求的参数name # some actions instance.save() return instance class Meta: model = Student fields = (‘id‘, ‘name‘, ‘age‘, ‘school‘) read_only_fields = (‘id‘, ‘age‘)
address = serializers.CharField(source="school.address", default=None)
status = serializers.SerializerMethodField() def get_status_verbose(self, obj): # obj表示当前模型对象 return obj.get_status_display()
标签:foreign 建模 false rom 信息 姓名 odi contex from
原文地址:https://www.cnblogs.com/qicun/p/10079490.html