Django之models操作数据库
一、创建数据库及链接数据库
(1)在models.py中创建数据库
from django.db import models
class UserType(models.Model):
name = models.CharField(max_length=32)
def __str__(self):
return self.name
class UserInfo(models.Model):
nid = models.AutoField(primary_key=True)
user = models.CharField(max_length=30)
email = models.EmailField()
memo = models.TextField()
img = models.ImageField()
user_type = models.ForeignKey(UserType,null=True,blank=True)
(2)在settings.py里面注册app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cmdb' ]
(3) 在settings.py修改数据库连接
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
(4)执行命令生成数据库
python3 manage.py makemigrations python3 manage.py migrate
二、利用django的admin功能
(1)在admin.py中添加:
from django.contrib import admin from cmdb import models admin.site.register(models.UserInfo)
admin.site.register(models.UserType)
(2)创建一个超级用户
python3 manage.py createsuperuser
(3)在urls.py中指定url路由规则
urlpatterns = [ url(r'^admin/', admin.site.urls), ]
(4)启动django
python3 manage.py runserver 0.0.0.0:8000
三、建立多对多关系
class Boy(models.Model): name = models.CharField(max_length=32) class Girl(models.Model): name = models.CharField(max_length=32) #方法一:在Girl中添加以下,自动建立多对多关系 f = models.ManyToManyField(Boy) #方法二:再创建一个新的表 class B2G(models.Model): boy = model.ForeignKey('Boy') girl = model.ForeignKey('Girl')