Home  >  Article  >  Database  >  django modifies mysql data

django modifies mysql data

藏色散人
藏色散人Original
2020-11-03 10:44:433481browse

Solutions for Django to modify mysql data: 1. Django establishes a database model; 2. Modify mysql data through the statement "user = User.objects.get(id=9) #user.username = '1234'" ; 3. Save the changes.

django modifies mysql data

Recommended: "mysql video tutorial"

Django's addition, deletion, modification and query of mysql database,

Django mysql automatically generates table commands

#Establish mapping

python manage.py makemigrations

#Into database

python manage.py migrate

django allows external ip to access services

python manage.py runserver 0.0.0.0:8000

Django creates database Model

from django.db import models
class Table_Test(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=200)
    class Meta:
        db_table = "test"

Common sql operations

#入库操作(增)
#建立实例
#user = User(username='新用户',password='你好')
#入库操作
#user.save()
#删除数据(删)
#User.objects.filter(username='新用户').delete()
#修改数据(改) 第一种方式
#user = User.objects.get(id=9)
#修改字段
#user.username = '1234'
#保存修改
#user.save()
#修改数据(改) 第二种方式
#return HttpResponse('',status=403)
#User.objects.filter(id=9).update(password='新密码')
#查询全部数据 翻译为 select * from user; all()返回值是list
res = User.objects.all()
#print(res)
#查询限定条件的数据 翻译为 select * from user where username = '新用户123' and逻辑使用多个参数传递
res = User.objects.filter(username='新用户',password='你好')
#print(res)
#只取一条 翻译 select * from user where id = 1
res_one = User.objects.get(id=1)
#print(res_one)
#排除条件  翻译为 select * from user where username != &#39;新用户123&#39;   <>
res = User.objects.exclude(username=&#39;新用户&#39;)
#定制字段显示 翻译为 select password from user where name = &#39;新用户&#39;
res_s = User.objects.filter(username=&#39;新用户&#39;).values(&#39;password&#39;)
#排序 翻译为 select * from user order by id asc  倒序使用 reverse()
res = User.objects.filter(username=&#39;新用户&#39;).order_by("password").reverse()
#去重 翻译为 select distinct(username) from user where username = &#39;新用户&#39;
res_dis = User.objects.filter(username=&#39;新用户&#39;).values(&#39;username&#39;).distinct()
#print(res_dis)
#取数量 翻译为 select count(*) from user
res_count = User.objects.filter(username=&#39;新用户&#39;).count()
print(res_count)

The above is the detailed content of django modifies mysql data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn