Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to add, delete, modify and check in python Django

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to add, delete, modify and check python Django. It is very detailed and has a certain reference value. Interested friends must finish reading it!

1. First create an app child python.\ manage.py startapp app01

Then create a data model

Under app01

Modules.py file

From django.db import models# Create your models here.class UserInfo (models.Model): name=models.CharField (max_length=32) password=models.CharField (max_length=12) age=models.IntegerField () tel=models.IntegerField (max_length=11)

Configuration database

'default': {' ENGINE': 'django.db.backends.mysql',' NAME':', 'USER':' database user name', 'PASSWORD':' password', 'HOST':' 127.0.0.1', 'PORT':' 3306',} 2. Migrate the database python manage.py makemigrations and python manage.py migrate3. Write routing urlfrom django.contrib import adminfrom django.urls import path,includefrom app01 import viewsurlpatterns = [# path ('admin/', admin.site.urls), # path (' index/',views.index), # path ('user/list/', views.user_list), # path (' login/', views.ApiLogin.as_view ()), # path ('del/', views.ApiDel.as_view ()), path (' add/') Views.addUser.as_view (), path ('user/', views.UserList.as_view ()), path (' updateuser/', views.upDateUser.as_view ()), path ('del/', views.deluser.as_view ()),] 4.view pages are written to add, delete, change and check from django.shortcuts import render HttpResponsefrom rest_framework.views import APIView# Create your views here.from django import viewsfrom app01.models import UserInfofrom rest_framework.response import Responsefrom app01.ser import APIViewUserInfoclass addUser (APIView): def post (self,request): obj=APIViewUserInfo (data=request.data) if obj.is_valid (): obj.save () return Response ({"data": obj.data, "status": 201 "message": "add user successfully"}) return Response (data=obj.errors,status=400) class UserList (APIView): def get (self,request): obj=UserInfo.objects.all () ser=APIViewUserInfo (instance=obj,many=True) return Response (ser.data) class upDateUser (APIView): def post (self) Request): print (request.data.get ('id')) i=request.data.get (' id') try: user=UserInfo.objects.get (id=i) except Exception as e: return Response (data=' does not exist', status=201) # create serialized object And pass the deserialized data to the data construction parameters Then verify user.password=request.data.get ('password') if request.data.get (' name')! ='': print (request.data.get ('name') = ='') user.name=request.data.get ('name') user.save () return Response (status=400) class deluser (APIView): def post (self) Request): id=request.data.get ('id') UserInfo.objects.filter (id=id). Delete () return Response ({"msg":' deleted successfully', "state": "true"}) # def index (request): # return HttpResponse ("Welcome") # def user_list (request): # return render (request, "user_list.html") # # class ApiLogin (APIView): # def get (self Request): # return HttpResponse ('get') # def post (self,request): # UserInfo.objects.create (name=' Zhang San', password='123456',age=15,tel='1234567891') # obj=UserInfo.objects.all () # print (obj) # return HttpResponse ('post') # # class ApiDel (APIView): # def post (self Request): # UserInfo.objects.filter (id=4). Delete () # return HttpResponse ('deleted successfully') 5. Serialization deserialization #-*-coding: utf-8-*-from rest_framework import serializersfrom app01.models import UserInfoclass APIViewUserInfo (serializers.Serializer): "Book data serializer"id = serializers.IntegerField (label='ID', read_only=True) # Primary key serialization # first: ordinary field serialization name = serializers.CharField (label=' name') Max_length=20) password = serializers.CharField (label=' password') age = serializers.IntegerField (label=' Age', required=False) tel = serializers.IntegerField (label=' phone', required=False) # # second: one-to-many field serialization # heroinfo_set = serializers.PrimaryKeyRelatedField (read_only=True Many=True) # # third: custom display (display many-to-many) # xxx = serializers.SerializerMethodField (read_only=True) class Meta: model = UserInfo # Custom display many-to-many fields # define creation syntax: ser.save () execute The create method is immediately called to create the data def create (self, validated_data):''validated_data: the form or vue request carries the json: {"username": "zhangsan", "password": "123456"}' 'return self.Meta.model.objects.create (* * validated_data). These are all the contents of the article "how to add, delete, modify and check python Django". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report