第04章节-Python3.5-创建一对多表结构
-
首先创建Django工程:
1.file->New Project
2.创建static目录和templates目录
3.创建app01(python manage.py startapp app01)
Microsoft Windows [版本 10.0.16299.492]
(c) 2017 Microsoft Corporation。保留所有权利。
(c) 2017 Microsoft Corporation。保留所有权
利。
(python3) C:\Users\Administrator\PycharmProjects\s14day20>python manage.py startapp app01
(python3) C:\Users\Administrator\PycharmProjects\s14day20>
4.配置settings.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
配置完成后想要写一个主机跟公司管理
- 1.创建表:
(python manage.py makemigrations)
(python manage.py migrate)
- model.py:
from django.db import models
# Create your models here.
# 公司
class Business(models.Model):
# id
caption = models.CharField(max_length=32)
# 主机
class Host(models.Model):
nid = models.AutoField(primary_key=True)
hostname = models.CharField(max_length=32,db_index=True)
# GenericIPAddressField(Field)字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6
ip = models.GenericIPAddressField(protocol="ipv4",db_index=True)
port = models.IntegerField()
b = models.ForeignKey(to="Business", to_field='id')
-
按方向键(↓)就能添加且id能自增
-
当又想在数据库添加目录是出现这种情况时候(python manage.py makemigrations
):
-
a.当选1时,然后提示要输入字符串(1选项是添加默认数据):
然后再执行(python manage.py migrate),打开Navicat查看效果:
-
上述出现的问题另一种解决方法:
- 就不会出现上面选择的问题