Django 简明教程
Django - Models
模型是一个代表我们 DB 中的表或集合的类,其中类的每个属性都是表或集合的字段。模型在 app/models.py 中定义(在我们的示例中:myapp/models.py)
A model is a class that represents table or collection in our DB, and where every attribute of the class is a field of the table or collection. Models are defined in the app/models.py (in our example: myapp/models.py)
Creating a Model
以下是作为示例创建的一个 Dreamreal 模型 −
Following is a Dreamreal model created as an example −
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"
每个模型都从 django.db.models.Model 继承。
Every model inherits from django.db.models.Model.
我们的类有 4 个属性(3 个 CharField 和 1 个 Integer),这些将作为表字段。
Our class has 4 attributes (3 CharField and 1 Integer), those will be the table fields.
带有 db_table 属性的 Meta 类允许我们定义实际表或收藏名称。Django 自动为表或集合命名:myapp_modelName。此类将允许你按自己的喜好强制设置表名。
The Meta class with the db_table attribute lets us define the actual table or collection name. Django names the table or collection automatically: myapp_modelName. This class will let you force the name of the table to what you like.
在创建模型后,你需要 Django 来生成实际数据库 −
After creating your model, you will need Django to generate the actual database −
$python manage.py syncdb
Manipulating Data (CRUD)
我们创建一个“crudops”视图来了解如何在模型中执行 CRUD 操作。此时我们的 myapp/views.py 如下所示 −
Let’s create a "crudops" view to see how we can do CRUD operations on models. Our myapp/views.py will then look like −
myapp/views.py
myapp/views.py
from myapp.models import Dreamreal
from django.http import HttpResponse
def crudops(request):
#Creating an entry
dreamreal = Dreamreal(
website = "www.polo.com", mail = "sorex@polo.com",
name = "sorex", phonenumber = "002376970"
)
dreamreal.save()
#Read ALL entries
objects = Dreamreal.objects.all()
res ='Printing all Dreamreal entries in the DB : <br>'
for elt in objects:
res += elt.name+"<br>"
#Read a specific entry:
sorex = Dreamreal.objects.get(name = "sorex")
res += 'Printing One entry <br>'
res += sorex.name
#Delete an entry
res += '<br> Deleting an entry <br>'
sorex.delete()
#Update
dreamreal = Dreamreal(
website = "www.polo.com", mail = "sorex@polo.com",
name = "sorex", phonenumber = "002376970"
)
dreamreal.save()
res += 'Updating entry<br>'
dreamreal = Dreamreal.objects.get(name = 'sorex')
dreamreal.name = 'thierry'
dreamreal.save()
return HttpResponse(res)
Other Data Manipulation
我们探索其他可以在模型上执行的操作。请注意,CRUD 操作是在我们模型的实例上执行的,现在我们将直接使用表示我们模型的类。
Let’s explore other manipulations we can do on Models. Note that the CRUD operations were done on instances of our model, now we will be working directly with the class representing our model.
我们在 myapp/views.py 中创建一个“datamanipulation”视图
Let’s create a 'datamanipulation' view in myapp/views.py
from myapp.models import Dreamreal
from django.http import HttpResponse
def datamanipulation(request):
res = ''
#Filtering data:
qs = Dreamreal.objects.filter(name = "paul")
res += "Found : %s results<br>"%len(qs)
#Ordering results
qs = Dreamreal.objects.order_by("name")
for elt in qs:
res += elt.name + '<br>'
return HttpResponse(res)
Linking Models
Django ORM 提供 3 种链接模型的方法 −
Django ORM offers 3 ways to link models −
我们在这里看到的第一个案例之一是一对多关系。如你所见,在上面的示例中,Dreamreal 公司可以拥有多个在线网站。定义该关系是通过使用 django.db.models.ForeignKey 来完成的 −
One of the first case we will see here is the one-to-many relationships. As you can see in the above example, Dreamreal company can have multiple online websites. Defining that relation is done by using django.db.models.ForeignKey −
myapp/models.py
myapp/models.py
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()
online = models.ForeignKey('Online', default = 1)
class Meta:
db_table = "dreamreal"
class Online(models.Model):
domain = models.CharField(max_length = 30)
class Meta:
db_table = "online"
如你在我们更新的 myapp/models.py 中看到的,我们添加了 online 模型并将其链接到了我们的 Dreamreal 模型。
As you can see in our updated myapp/models.py, we added the online model and linked it to our Dreamreal model.
我们通过 manage.py shell 检查所有这一切的工作原理 −
Let’s check how all of this is working via manage.py shell −
首先,让我们在 Django shell 中创建一些公司(Dreamreal 条目)来进行测试 −
First let’s create some companies (Dreamreal entries) for testing in our Django shell −
$python manage.py shell
>>> from myapp.models import Dreamreal, Online
>>> dr1 = Dreamreal()
>>> dr1.website = 'company1.com'
>>> dr1.name = 'company1'
>>> dr1.mail = 'contact@company1'
>>> dr1.phonenumber = '12345'
>>> dr1.save()
>>> dr2 = Dreamreal()
>>> dr1.website = 'company2.com'
>>> dr2.website = 'company2.com'
>>> dr2.name = 'company2'
>>> dr2.mail = 'contact@company2'
>>> dr2.phonenumber = '56789'
>>> dr2.save()
现在是一些托管域名 −
Now some hosted domains −
>>> on1 = Online()
>>> on1.company = dr1
>>> on1.domain = "site1.com"
>>> on2 = Online()
>>> on2.company = dr1
>>> on2.domain = "site2.com"
>>> on3 = Online()
>>> on3.domain = "site3.com"
>>> dr2 = Dreamreal.objects.all()[2]
>>> on3.company = dr2
>>> on1.save()
>>> on2.save()
>>> on3.save()
从在线域名访问托管公司(Dreamreal 条目)的属性很简单 −
Accessing attribute of the hosting company (Dreamreal entry) from an online domain is simple −
>>> on1.company.name
如果我们想了解 Dreamreal 中某公司托管的所有在线域名,我们将使用此代码 −
And if we want to know all the online domain hosted by a Company in Dreamreal we will use the code −
>>> dr1.online_set.all()
要获取 QuerySet,请注意我们之前见过的所有操作方法(filter、all、exclude、order_by……)
To get a QuerySet, note that all manipulating method we have seen before (filter, all, exclude, order_by….)
你还可以访问已链接模型属性以进行筛选操作,我们来假设你想获取 Dreamreal
名称包含 company
的所有在线域名 −
You can also access the linked model attributes for filtering operations, let’s say you want to get all online domains where the Dreamreal name contains 'company' −
>>> Online.objects.filter(company__name__contains = 'company'
Note − 这种类型的查询只受 SQL DB 支持。它不适用于不存在连接符且有两个 _
的非关系型数据库。
Note − That kind of query is just supported for SQL DB. It won’t work for non-relational DB where joins doesn’t exist and there are two '_'.
但这不是链接模型的唯一方式,你也有 OneToOneField
,一个保证两个对象之间关系唯一性的链接。如果我们在线示例中使用了 OneToOneField
,这意味着对于每个 Dreamreal
条目,只有一个 Online
条目是可能的,反之亦然。
But that’s not the only way to link models, you also have OneToOneField, a link that guarantees that the relation between two objects is unique. If we used the OneToOneField in our example above, that would mean for every Dreamreal entry only one Online entry is possible and in the other way to.
最后,有 ManyToManyField
用于表之间的 (n-n) 关系。请注意,这些与基于 SQL 的数据库有关。
And the last one, the ManyToManyField for (n-n) relation between tables. Note, those are relevant for SQL based DB.