ORM
1. Install
pip install mysqlclient # python<=3.5
pip install pymysql # python>3.5
2. connect
# mysite/settings.py
...
import pymysql # python>=3.5
pymysql.install_as_MySQLdb()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'table111',
'USER': 'root',
'PASSWORD': 'Root1234@',
'HOST': 'localhost',
'PORT': 3306,
}
}
...
3. CRUD
# models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_len=32)
passwd = models.CharField(max_len=64)
age = models.IntegerField()
"""
create table myapp_user(
id bigint auto_increment primary key,
name varchar(32),
passwd varchar(64),
age int
)
"""
Make sure that we have registered our ‘myapp’ in ‘mysite’ project.
python manage.py makemigrations
python manage.py migrate
If we update models by adding some new feilds, we have to either give a default value or make ’null=True’ available.
class User(models.Model):
name = models.CharField(max_len=32)
passwd = models.CharField(max_len=64)
age = models.IntegerField()
department = models.CharField(max_len=32, default="IT")
# create
User.objects.create(name="ww", passwd="123", age=23)
# delete
User.objects.filter(id=3).delete()
User.objects.all().delete()
# read
query = User.objects.all()
for obj in query:
print(obj.id, obj.name)
# update
User.objects.all().update(age=42)