Python Web开发:创建数据模型
来自CloudWiki
django常用字段
AutoField : 自动增长的IntegerField,通常不用指定,不指定时Django会自动创建属性名为id的自动增长属性。
BooleanField:布尔字段,值为True或False。
NullBooleanField:支持Null、True、False三种值
CharField:字符串。参数max_length表示最大字符个数
TextField:大文本字段,一般超过4000个字符时使用。
IntegerField:整数
DecimalField:十进制浮点数。参数max_digits表示总位数。参数decimal_places表示小数的位数。
FloatField:浮点数。参数同上。没有上面的精确度高
DateField:日期
1)auto_now表示每次保存时,自动设置该字段为当前时间,用于"最后一次修改"的时间戳,它总是使用当前日期,默认为false。
2)auto_now_add表示当对象第一次被创建时自动设置当前时间,用于创建的时间戳,它总是使用当前日期,默认为false。
3)auto_now_add和auto_now是相互排斥的,组合将会发生错误。只能二选一
DateTimeField:日期时间,参数同DateField。
FileField:上传文件字段。在声明时必须指定参数upload_to,该参数表明用于保存文件的本地路径。
ImageField:继承于FileField,对上传的内容进行校验,确保是有效的图片。它还有两个可选参数:height_field 和width_field ,如果提供了这两个参数,则图片会按指定的高度和宽度进行保存
URLField:用于保存URL
创建数据模型
创建数据模型
aboutApp/models.py:
在该文件中添加“荣誉模型”:
from django.db import models # Create your models here. class Award(models.Model): # 荣誉模型 description = models.TextField(max_length=500, blank=True, null=True)#文字描述 photo = models.ImageField(upload_to='Award/', blank=True) #图片
配置上传目录
其中关于文件的字段需要额外进行路径设置。
hengDaProject/settings.py末尾添加:
MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
同步数据库
创建数据同步文件:
python manage.py makemigrations
Migrations for 'aboutApp': aboutApp\migrations\0001_initial.py - Create model Award
进行数据库同步:
python manage.py migrate
Operations to perform: Apply all migrations: aboutApp, admin, auth, contenttypes, sessions Running migrations: Applying aboutApp.0001_initial... OK Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying sessions.0001_initial... OK
展望
接下来 可以通过代码、可视化界面 两种方式管理数据库里的数据。