Python学习笔记之Django创建第一个数据库模型的方法
作者:金阳 时间:2024-01-14 20:46:39
Django里面集成了SQLite的数据库,对于初期研究来说,可以用这个学习。
第一步,创建数据库就涉及到建表等一系列的工作,在此之前,要先在cmd执行一个命令:
python manage.py migrate
这个命令就看成一个打包安装的命令,它会根据mysite/settings.py的配置安装一系列必要的数据库表
第二步,我们要建立一个Model层,修改demo/model.py:
from django.db import models
classQuestion(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
classChoice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
这个Model的内容包括创建表(对象)、确定变量(字段)的类型,以及外键方面的信息
第三步,要激活Model,那么现在helloworld/setting.py中修改:
INSTALLED_APPS =[
'demo.apps.DemoConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
主要是加了第一行的内容,这个在demo/apps下有的。目的是让Django知道有demo这个app。
然后就在cmd下面运行:
python manage.py makemigrations demo
可以看到在demo/migrations/0001_initial.py下面生成了很多代码
继续run这段代码,就完成了建表工作:
python manage.py sqlmigrate demo 0001
再跑一下migrate命令,把这些model创建到数据库表中
python manage.py migrate
第四步,也是比较好玩的了,就是要进入到python django的shell中,执行这个命令:
python manage.py shell
在这个里面,就可以通过命令行操作数据库了
先引入刚才创建好的model:
from demo.models importQuestion,Choice
这个命令,打印出Question所有的对象:
Question.objects.all()
然后创建一个Question的对象(或数据):
from django.utils import timezone
q =Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
q.question_text
q.pub_date
q.question_text = "What's up?"
q.save()
Question.objects.all()
第五步,然后polls/models.py中添加以下代码:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible# only if you need to support Python 2
classQuestion(models.Model):
# ...
def __str__(self):
return self.question_text
@python_2_unicode_compatible# only if you need to support Python 2
classChoice(models.Model):
# ...
def __str__(self):
return self.choice_text
import datetime
from django.db import models
from django.utils import timezone
classQuestion(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now()- datetime.timedelta(days=1)
在这里__str__()是一个非常重要的方法,大概可以看成java里pojo对象的一个toString()方法
接下来,就可以在数据库中进行很多操作,在shell中输入以下的代码,就可以执行对数据库的增删查改:
from polls.models importQuestion,Choice
Question.objects.all()
Question.objects.filter(id=1)
Question.objects.filter(question_text__startswith='What')
from django.utils import timezone
current_year = timezone.now().year
Question.objects.get(pub_date__year=current_year)
Question.objects.get(id=2)
Question.objects.get(pk=1)
q =Question.objects.get(pk=1)
q.was_published_recently()
q =Question.objects.get(pk=1)
q.choice_set.all()
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.question
q.choice_set.all()
q.choice_set.count()
Choice.objects.filter(question__pub_date__year=current_year)
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete()
操作django Admin
Django的管理端可以管理站点、管理账户权限等等。
在cmd运行以下的脚本创建账户:
python manage.py createsuperuser
Username: admin
Email address: admin@example.com
Password:**********
Password(again):*********
Superuser created successfully.
启动server:
python manage.py runserver 8081
访问链接地址:
http://127.0.0.1:8081/admin/
登录界面:
管理界面:
在demo/admin.py中添加代码注册对象:
from django.contrib import admin
from.models importQuestion
admin.site.register(Question)
刷新后即增加这个对象:
点击Questions进去:
这样,就可以在图形化的界面中执行增删查改了。
来源:https://www.cnblogs.com/leejy/p/6745186.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用BootStrap和Metroui设计的metro风格微网站或手机app界面
![](https://img.aspxhome.com/file/2023/8/129558_0s.png)
Python3+Appium实现多台移动设备操作的方法
关于浮动的前世今生
![](https://img.aspxhome.com/file/UploadPic/20098/19/01-12s.png)
python机器学习理论与实战(六)支持向量机
![](https://img.aspxhome.com/file/2023/8/75168_0s.jpg)
PHP如何实现HTTP验证
Python import导入上级目录文件的方法
coreseek 搜索英文的问题详解
pandas通过索引进行排序的示例
conda与jupyter notebook kernel核环境不一致的问题解决
![](https://img.aspxhome.com/file/2023/5/127095_0s.png)
Java使用正则表达式(regex)匹配中文实例代码
基于PyQT5制作一个桌面摸鱼工具
padas 生成excel 增加sheet表的实例
![](https://img.aspxhome.com/file/2023/2/118282_0s.jpg)
vue 实现setInterval 创建和销毁实例
![](https://img.aspxhome.com/file/2023/8/126398_0s.jpg)
python3.4爬虫demo
解决php-fpm.service not found问题的办法
python模块shutil函数应用示例详解教程
![](https://img.aspxhome.com/file/2023/2/110242_0s.png)
TensorFlow内存管理bfc算法实例
![](https://img.aspxhome.com/file/2023/1/130591_0s.jpg)
Python 数据结构之树的概念详解
![](https://img.aspxhome.com/file/2023/8/78798_0s.png)
使用Python画股票的K线图的方法步骤
![](https://img.aspxhome.com/file/2023/7/93737_0s.jpg)