Django项目中使用数据库
安装mysql数据库,启动数据库服务,创建数据库
setting.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_py1807a',
"USER": "root",
"PASSWORD": "root", # 若默认为空,删除这一行
"CHARSET": "utf8",
"HOST": "localhost",
"PORT": 3306,
}
}
迁移数据
将我们定义的数据告诉数据库,由数据库生成对应的表
1)、python manage.py makemigrations# django生成迁移文件
2)、Python manage.py migrate # 将数据同步到数据库上
#查询迁移文件生成的SQL:python manage.py sqlmigrate blog num
操作数据
Django操作数据库有三种方式
views.py
def add_user(request):
# 首先需要接收页面传递过来的参数
username = 'zhaowu'
age = 16
password = '123456'
email = '110@qq.com'
try:
# 第一种方式,使用类方法的方式完成数据的操作
# user = models.User.create_user(username=username, \
# password=password, age=age, email=email)
# user.save()
# return HttpResponse('<h2>用户添加成功</h2>')
#第三种,使用面向过程的方式实现
# 因为model类继承了我们的Model类,在Model类中有大量的方法
# user = models.User(username=username,password=password,\
# age=age, email=email)
user= models.User.um.add_user(username=username, \
password=password, age=age, email=email)
print(user.id, user.username, user.password, user.email)
# user.save()
return HttpResponse('<h2>用户添加成功</h2>')
except:
return HttpResponse('<h2>用户添加失败</h2>')
models.py
# 第三种方法
class UserManager(models.Manager):
def add_user(self, username, password, age, email):
return self.create(username=username, password=password, age=age, email=email)
# Create your models here.
class User(models.Model):
id = models.AutoField(primary_key=True)
username = models.CharField(unique=True, max_length=255, verbose_name="用户姓名")
password = models.CharField(max_length=255, verbose_name="用户密码")
age = models.IntegerField(default=0, verbose_name="用户年龄")
nickname = models.CharField(max_length=255,null=True,blank=True)
birthday = models.DateTimeField(default=datetime.now(), verbose_name="用户生日")
email = models.EmailField(max_length=255, verbose_name="用户邮箱")
# 默认为0:男;1:女
gender = models.BooleanField(default=0)
um = UserManager()
# class Meta:
# db_table = 'blog_user'
# 第一种
@classmethod
def create_user(cls, username, password, age, email):
user = cls(username=username, password=password, age=age, email=email)
return user