美文网首页
Django中models模型(操作数据库)

Django中models模型(操作数据库)

作者: Tsukinousag | 来源:发表于2023-01-02 13:00 被阅读0次

1. 建立模型

from django.db import models

# Create your models here.

class Mysql(models.Model):
    name=models.CharField(max_length=20)
    birthday=models.DateField()
    number=models.CharField(max_length=13,null=True)
    address=models.CharField(max_length=20,null=True)

#以后开发中如果想要对表结构进行调整
'''
python manage.py makemigrations
python manage.py migrate
'''

2. 建立同级目录下的test.py文件

3. test.py中用model操作数据库

#utf-8
from mysql_app.models import Mysql

####################create data
cl=Mysql(name='rose',birthday='1998-01-01',number='13312345678',address='beijing')
cl.save()
Mysql.objects.create(name='hjb',birthday='1999-08-22',number='15990186973',address='hangzhou')

###################delete data
cl=Mysql.objects.filter(name='rose').delete()

##################delete all data
Mysql.objects.all().deleter()

###################update sql
Mysql.objects.filter(id=3).update(address='chengdu')
Mysql.objects.all().update(birthday='2023-1-2')
Mysql.objects.filter(name='rose').update(name='tony')

###################select first data
cl=Mysql.objects.filter(id=3).first()
cl_add=Mysql.objects.filter(id=3).first().address
print(cl,cl_add)
In [16]: Mysql object (3) chengdu

##################select all data
cl_all=Mysql.objects.all()
print(cl_all)
 <QuerySet [<Mysql: Mysql object (3)>, <Mysql: Mysql object (4)>, <Mysql: Mysql object (5)>, <Mysql: Mysql object (6)>]>

相关文章

网友评论

      本文标题:Django中models模型(操作数据库)

      本文链接:https://www.haomeiwen.com/subject/gnjccdtx.html