Home >Backend Development >Python Tutorial >Python Django model establishment and operation (detailed examples)
This article brings you relevant knowledge about Python, which mainly introduces the relevant content about Django model establishment and operation. Let's take a look at it together. I hope it will be helpful to everyone.
[Related recommendations: Python3 video tutorial]
We want to build a blog system , first use the command python manage.py startapp blog
in the directory where manage.py is located to create a new blog application, and then write a class in ./blog/models.py
, Name it BlogArticles
.
Through this class we can create a database table specifically used to save blog posts. The code is as follows:
from django.db import modelsfrom django.utils import timezone # 新增from django.contrib.auth.models import User # 新增# Create your models here.# 编写博客的数据类型类BlogArticlesclass BlogArticles(models.Model): # 字段title的属性为CharField()类型,并且以参数max_length=300说明字段的最大数量 title = models.CharField(max_length=300) # 一个用户对应多篇文章,级联删除 author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") body = models.TextField() publish = models.DateTimeField(default=timezone.now) class Meta: ordering = ("-publish", ) # 规定了BlogArticles实例对象的显示顺序,即按照publish字段值的倒序显示 def __str__(self): return self.title
I believe that after the introduction in the previous article, many of the faces here are familiar to you. Now let’s briefly introduce them:
TIME_ZONE = 'Asia/Shanghai' # 设置东八区时间# TIME_ZONE = 'UTC'USE_TZ = False
User
The model is named as the built-in application is called auth, which starts with The namespace django.contrib.auth
appears in the INSTALL_APPS
configuration ForeignKey()
, reflecting that a user can publish multiple articles. , where the parameter on_delete=models.CASCADE
is the "cascade delete" in the database. If a user in the "User Table" is deleted, then the article record corresponding to the user in the "Article Table" will also Will be deleted. related_name="blog_posts"
is used to allow an instance of User (a certain username) to reversely query an instance of the class BlogArticles using the "blog_posts" attribute. ordering = ("-publish", )
to specify the display order of articles__str__
method is the string representation of the object. We can use the name of the section to represent it. In the above steps, we still just wrote a blog post model in the blog application we created. If we want the application to take effect, we also need to configure the application into our settings. In settings.py
Add the blog application to the INSTALLED_APPS
list of the file, as follows:
BlogArticles
class After the data model is written, our database table is created through the fields and attributes in this class.
The next step is to tell Django that my model class has been created and it’s time for you to create the database. Let’s open the terminal and go to manage.py
The folder where the file is located, and then run the command:
python manage.py makemigrations
Then you will see the following output:
Migrations for 'blog': blog/migrations/0001_initial.py - Create model BlogArticles
At this time, Django is in the /blog/migrations
directory A file named 0001_initial.py
is created in . It represents the current state of the application model, and in the next step, this file will be used to create tables and columns.
The migration file will be translated into SQL statements. Execute the following command:
python manage.py sqlmigrate blog 0001
Then you can see the following output:
BEGIN; -- -- Create model BlogArticles -- CREATE TABLE "blog_blogarticles" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(300) NOT NULL, "body" text NOT NULL, "publish" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED); CREATE INDEX "blog_blogarticles_author_id_ed798e23" ON "blog_blogarticles" ("author_id"); COMMIT;
Finally, we apply the produced migration file to the database:
python manage.py migrate
When you see
Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions Running migrations: ... Applying sessions.001_initial... OK
Applying sessions.001_initial... OK
, this is the migration script we produced in the previous step. This means that our database is ready for use.
Django comes with a database SQLite. It should be noted that SQLite is a product-level database. SQLite is used by many companies in thousands of products, such as all Android and iOS devices, major web browsers, Windows 10, MacOS, and more. But this is not suitable for every situation. SQLite cannot be compared to databases such as MySQL, PostgreSQL or Oracle. High-volume websites, write-intensive applications, large data sets, and high-concurrency applications using SQLite will eventually cause problems.
SQLite is very lightweight, but it does not affect our use for learning. Next we will use command line tools to operate the model, that is, we have learned the basic operations of the database - adding , delete, modify, check.
In the above content, a blog article model is established, and then we create our corresponding database table through data migration, and then add, delete, and modify some operations based on the above model. , this small part of the content may require everyone to be a little familiar with database operations. I believe that everyone is reading this set of introductory notes with the purpose of learning Django. I don’t dare to do anything in front of the database tycoons, so I will go directly to this chapter.
对数据库的操作可以利用 GUI 工具,也可以通过命令行 sqlite3 db.sqlite3
,我们在 db.sqlite3 所在的目录下使用上述命令,就可以进入到 db.sqlite3 数据库,如果本地开发中没有配置 SQLite 环境,可以自行搜索如何配置。
如果我们输入命令,看到如下信息,说明进入成功:
~/DjangoProject/myblog $ sqlite3 db.sqlite3 SQLite version 3.29.0 2019-07-10 17:32:03 Enter ".help" for usage hints. sqlite>
然后我们使用 .tables
即可查看当前数据库中的数据库表的名称,除了 blog_blogarticles
是我们通过 BlogArticles 模型建立的,其余的都是项目默认创建的数据库表。
~/DjangoProject/myblog $ sqlite3 db.sqlite3 SQLite version 3.29.0 2019-07-10 17:32:03 Enter ".help" for usage hints. sqlite> .tables auth_group blog_blogarticles auth_group_permissions django_admin_log auth_permission django_content_type auth_user django_migrations auth_user_groups django_session auth_user_user_permissions sqlite>
接下来使用 pragma table_info(blog_blogarticles);
命令来查看 blog_blogarticles 表的结构:
sqlite> .header on sqlite> pragma table_info(blog_blogarticles); cid|name |type |notnull|dflt_value|pk 0| id |integer |1 | |1 1|title |varchar(300)|1 | |0 2|body |text |1 | |0 3|publish |datetime |1 | |0 4|author_id|integer |1 | |0 sqlite>
.header on 开启头部显示
SQLite 的
PRAGMA
命令是一个特殊的命令,可以用在 SQLite 环境内控制各种环境变量和状态标志。一个 PRAGMA 值可以被读取,也可以根据需求进行设置。
我们可以大致查看上面的表结构,cid 是指列 id,name 是指列名,type 是指列类型,notnull 非空,值为 1 表示 True,dflt_value 是指 default 默认值(这一列没有值,说明设置设置默认值),pk 是指 primary_key 主键。
大家可以跟我们在前一章中的数据模型 BlogArticles 所规定的字段和属性进行对比,是不是刚好我们利用数据迁移成功将数据模型转化为数据库表。
我们可以在命令行中输入 python manage.py createsuperuser
创建一个 Django 超级管理员,输入用户名和密码,当提示 Superuser created successfully,创建成功。如下:
~/DjangoProject/myblog $ python manage.py createsuperuser Username (leave blank to use 'yuzhou_1su'): zoeu Email address: test@test.com Password: Password (again): Superuser created successfully.
然后我在浏览器输入 http://127.0.0.1:8000/admin/
,就可以打开如下界面:
输入刚才创建的超级管理员的用户名和密码就可以进入系统,如图:
Groups 和 Users 是 Django 在用户管理应用中默认的用户分类。为了让我们得管理员用户能够发布博客,我们需要在 ./blog/admin.py
文件中,加入如下代码:
from django.contrib import admin# 新增,将BlogArticles类引入到当前环境中from .models import BlogArticles # 将BlogArticles注册到admin中admin.site.register(BlogArticles)
刷新页面,我们可以得到如下的页面:
超级管理员界面先放在这,我们回到模型操作。
使用 Python 进行开发的一个重要优点是交互式 shell。我们在 ./blog/models.py
中创建了数据模型后,Django 就会自动提供数据库抽象的 API,这是一种快速尝试和试验 API 的方法。通过这个 API 我们可以快速创建、获取、修改和删除对象,对此我们称之为 ORM(Object-Relational Mapper)
我们可以使用 manage.py
工具加载我们的项目来启动 Python shell :
python3 manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>>
请特别注意我们进入 shell 的方式,不是直接在命令行中敲 python3,虽然这与直接输入 python 指令来调用交互式控制台是非常相似。
区别是我们利用 manage.py 工具,将项目将被添加到 sys.path
并加载 Django。这意味着我们可以在项目中导入我们的模型和其他资源并使用它。
让我们从导入 BlogArticles 类开始:下面就可以开始我们对数据库的增、删、改、查等操作。
$ python3 manage.py shell Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwinType "help", "copyright", "credits" or "license" for more information. (InteractiveConsole)>>> from django.contrib.auth.models import User>>> from blog.models import BlogArticles>>> admin = User.objects.get(username="zoue")>>> admin.username'zoeu'>>> admin.id1>>> admin.password'pbkdf2_sha256$150000$b9j0ZKBVZSo1$l+fEIiKIaS6u1mhjMPOX1qR0xMOaemnRJIwiE2lNn60='>>> admin.email'test@test.com'>>> type(admin) <class></class>
以上是对用户的查询操作是不是刚好是我们上一节中在创建管理员的内容,恭喜你!
接下来,我们对博客文章进行操作,要创建新的 BlogArticle 对象,我们可以执行以下操作:
>>> BlogAriticle01 = BlogArticles(title ='DjangoNotes_Day01', author=zoue, body='Django是啥?');
为了将这个对象保存在数据库中,我们必须调用 save 方法:
>>> BlogAriticle01.save()
save
方法用于创建和更新对象。这里Django创建了一个新对象,因为这时 BlogAriticle01 实例没有 id。第一次保存后,Django 会自动设置 ID :
>>> BlogAriticle01.id4
因为我自己在之前创建过其它文章,所以这个 id 值为 4,如果你是按照本入门笔记一步步操作过来,id 值应该为 1。
当然,还可以查看其它属性,这里统一将命令敲出来:
>>> BlogAriticle01.title'DjangoNotes_Day01'>>> BlogAriticle01.author <user:>>>> BlogAriticle01.body'Django是啥?'>>> BlogAriticle01.publish datetime.datetime(2019, 9, 30, 19, 56, 58, 735676)>>></user:>
每个 Django 模型都带有一个特殊的属性; 我们称之为模型管理器(Model Manager)。你可以通过属性 objects 来访问这个管理器,它主要用于数据库操作。例如,我们可以使用它来直接创建一个新的 Board 对象:
>>> BlogArticle02 = BlogArticles.objects.create(title='Python', author=admin, body='Head First to Python.')>>> BlogArticle02.id5
要更新一个值,我们可以利用如下操作:
>>> BlogAriticle01.body = 'I love Django, 但是我太难了'>>> BlogAriticle01.body'I love Django, 但是我太难了'
>>> blogs = BlogArticles.objects.all()>>> blogs <queryset>, <blogarticles:>, <blogarticles:>, <blogarticles:>, <blogarticles:>]></blogarticles:></blogarticles:></blogarticles:></blogarticles:></queryset>
结果是一个 QuerySet,我们可以将这个 QuerySet 看作一个列表。假设我们想遍历它并打印每个模块的标题。
>>> for blog in blogs:... print(blog.title)... Python DjangoNotes_Day01 right here waiting Yesterday once more You Raise me up>>>
同样,我们可以使用模型的 管理器(Manager) 来查询数据库并返回单个对象。为此,我们要使用 get 方法:
>>> BlogArticles.objects.get(id=5) <blogarticles:></blogarticles:>
>>> BlogArticles.objects.get(id=5).delete() (1, {'blog.BlogArticles': 1})
删除后再重新查看一下 QuerySet,发现没有了
>>> blogs = BlogArticles.objects.all()>>> blogs <queryset>, <blogarticles:>, <blogarticles:>, <blogarticles:>]></blogarticles:></blogarticles:></blogarticles:></queryset>
除了 get 方法,其实也可以用 filter 进行筛选查询 id=5 然后删除,
BlogArticles.objects.filter(id=5).delete()
,关于 filter 方法我们将在后面的文章中进行介绍。
下面是我们在本节中关于模型学到的方法和操作,使用 BlogArticles 模型作为参考。大写的 BlogArticles 指的是类,BlogArticles01 指 BlogArticles 的一个实例(或对象):
操作 | 代码示例 |
---|---|
创建一个对象而不保存 | BlogAriticle01 = BlogArticles() |
保存一个对象(创建或更新) | BlogAriticle01.save() |
数据库中创建并保存一个对象 | BlogArticle02 = BlogArticles.objects.create(title='...', author=..., body='...') |
列出所有对象 | BlogArticles.objects.all() |
通过字段标识获取单个对象 | BlogArticles.objects.get(id=5) |
通过字段标识删除单个对象 | BlogArticles.objects.get(id=5).delete() |
【相关推荐:Python3视频教程 】
The above is the detailed content of Python Django model establishment and operation (detailed examples). For more information, please follow other related articles on the PHP Chinese website!