Django 简明教程
Django – Insert Data
Django 有自己的对象关系模型 (ORM),它将 Python 类与关系数据库中的表进行映射。ORM 机制有助于以面向对象的方式执行 CRUD 操作。在本章中,我们将学习插入新数据的不同方法。
Django has its own Object Relation Model (ORM) that maps a Python class with a table in a relational database. The ORM mechanism helps in performing CRUD operations in object-oriented manner. In this chapter, we shall learn about different methods of inserting a new data.
By default, Django uses a SQLite database 。Django 中的模型是从“django.db.models”类继承的类。
By default, Django uses a SQLite database. A model in Django is a class inherited from the "django.db.models" class.
让我们在“models.py”文件中使用以下 Dreamreal model 来了解如何在映射表中插入数据:
Let us use the following Dreamreal model in "models.py" file for learning how to insert data in the mapped table −
from django.db import models
class Dreamreal(models.Model):
website = models.CharField(max_length=50)
mail = models.CharField(max_length=50)
name = models.CharField(max_length=50)
phonenumber = models.IntegerField()
class Meta:
db_table = "dreamreal"
在声明一个模型后,我们需要执行 migrations ——
After declaring a model, we need to perform the migrations −
python manage.py makemigrations
python manage.py migrate
Insert Object From Shell
Django 具有一个有用的功能,可以使用此功能在 Django 项目的环境中调用 Python shell。使用命令 manage.py 与脚本一起使用 shell 命令 -
Django has a useful feature with which you can invoke a Python shell inside the Django project’s environment. Use the shell command with the manage.py script −
python manage.py shell
在 Python 提示符前,导入 Dreamreal 模型 -
In front of the Python prompt, import the Dreamreal model −
>>> from myapp.models import Dreamreal
我们可以构造此类的对象并调用其 save() 方法,这样就会在表中添加相应的行
We can construct an object of this class and call its save() method so that the corresponding row is added in the table
>>> obj = Dreamreal(website="www.polo.com", mail="sorex@polo.com", name="sorex", phonenumber="002376970")
>>> obj.save()
我们可以通过在任何 SQLite 查看器中打开数据库来确认这一点。
We can confirm this by opening the database in any SQLite viewer.
你还可以使用模型类的 objects 属性的 create() 方法来插入记录。
You can also use the create() method of the objects attribute of the model class to insert the record.
>>> obj = Dreamreal.objects.create(website="www.polo.com",
mail="sorex@polo.com", name="sorex", phonenumber="002376970")
Perform Insert Operation by Calling a View Function
现在,让我们通过调用 View 函数来执行插入操作。在 views.py 文件中定义 addnew() 函数如下——
Let us now perform the insert operation by calling a View function. Define addnew() function in views.py file as follows −
from myapp.models import Dreamreal
def addnew(request):
obj = Dreamreal(website="www.polo.com", mail="sorex@polo.com", name="sorex", phonenumber="002376970")
obj.save()
return HttpResponse("<h2>Record Added Successfully")
我们需要使用 URLpatterns 列表注册此 View。
We need to register this View with the URLpatterns list.
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("addnew/", views.addnew, name='addnew')
]
与上面示例中使用硬编码值不同,我们希望接受用户输入的数据。为此,请在 myform.html 文件中创建一个 HTML 表单。
Instead of using the hard-coded values as in the above example, we would like the data to be accepted from the user. For this purpose, create an HTML form in myform.html file.
<html>
<body>
<form action="../addnew/" method="post">
{% csrf_token %}
<p><label for="website">WebSite: </label>
<input id="website" type="text" name="website"></p>
<p><label for="mail">Email: </label>
<input id="mail" type="text" name="mail"></p>
<p><label for="name">Name: </label>
<input id="name" type="text" name="name"></p>
<p><label for="phonenumber">Phone Number: </label>
<input id="phonenumber" type="text" name="phonenumber"></p>
<input type="submit" value="OK">
</form>
</body>
</html>
HTML 模板文件必须存储在 TEMPLATES 设置中定义的目录中——
The HTML template file must be stored in a directory defined in the TEMPLATES setting −
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/'templates'],
.. . .,
]
让我们使用 render() 函数显示表单模板——
Let us use the render() function to display the form template −
from django.shortcuts import render
from myapp.models import Dreamreal
def addnew(request):
if request.method == "POST":
ws = request.POST['website']
mail = request.POST['mail']
nm = request.POST['name']
ph = request.POST['phonenumber']
obj = Dreamreal(website=ws, mail=mail, name=nm, phonenumber=ph)
obj.save()
return HttpResponse("<h2>Record Added Successfully</h2>")
return render(request, "myform.html")
请注意,表单的 action 属性也设置为与 addnew() 函数映射的同一 URL。因此,我们需要检查 request.method。如果它是 GET 方法,则会呈现空白表单。如果它是 POST 方法,则会分析表单数据并用于插入新记录。
Note that the form’s action attribute is also set to the same URL mapping the addnew() function. Hence, we need to check the request.method. If it’s GET method, the blank form is rendered. If it’s POST method, the form data is parsed and used for inserting a new record.
The Model Form
Django 有一个 ModelForm 类,可以自动呈现 HTML 表单,其结构与模型类的属性相匹配。
Django has a ModelForm class that automatically renders a HTML form with its structure matching with the attributes of a model class.
我们在 app 文件夹中的 forms.py 文件中定义一个 DreamRealForm 类,它使用 Dreamreal model 作为基础。
We define a DreamRealForm class in forms.py file under the app folder that uses the Dreamreal model as the basis.
from django import forms
from .models import Dreamreal
class DreamrealForm(forms.ModelForm):
class Meta:
model = Dreamreal
fields = "__all__"
模型表单的对象会呈现给 HTML 表单。如果请求方法是 POST,ModelForm 类的 save() 方法会自动验证表单并保存新记录。
An object of the model form is rendered on the HTML form. In case the request method is POST, the save() method of the ModelForm class automatically validates the form and saves a new record.
from .forms import DreamrealForm
def addnew(request):
if request.method == 'POST':
form = DreamrealForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("<h2>Book added successfully</h2>")
context={'form' : DreamrealForm}
return render(request, "myform.html", context)
The CreateView Class
Django 定义了通用视图类集合。 CreateView 类专门用于执行 INSERT 查询操作。
Django defines a collection of generic view classes. The CreateView class is specially designed for performing the INSERT query operation.
我们定义 CreateView 类的子类并将其 template_name 属性设置为我们已经创建的 myform.html 。
We define a subclass of CreateView class and set its template_name property to myform.html that we have already created.
将以下代码添加到 views.py 文件中−
Add the following code in views.py file −
from django.views.generic import CreateView
class DRCreateView(CreateView):
model = Dreamreal
fields = "__all__"
template_name = 'myform.html'
success_url = '../success/'
插入成功后,浏览器会被重定向到 success() 视图函数。
On successful insertion, the browser is redirected to the success() view function.
def success(request):
return HttpResponse("<h2>Book added successfully</h2>")
上面的这两个视图都必须包含在 urls.py 文件的 URL 模式列表中。通用视图类通过其 as_view() 方法注册。
Both the above views must be included in the URL pattern list of urls.py file. The generic view classes are registered with their as_view() method.
from django.urls import path
from . import views
from .views import DRCreateView
urlpatterns = [
path("", views.index, name="index"),
path("addnew/", views.addnew, name='addnew'),
path("add/", DRCreateView.as_view(), name='add'),
path("success/", views.success, name='success'),
]
在本章中,我们学习了在 Django 模型中插入数据的不同方法。
In this chapter, we learned the different ways to insert data in a Django model.