Django学习(三) Django模型创建以及操作

时间:2023-03-09 04:43:48
Django学习(三) Django模型创建以及操作

  

在Django中可以建立自己的模型Model,这里对应Java里的实体类,跟数据库表是对应的。其中用到了django.db模块中的models。如下图所示:  

 mysite/news/models.py
from django.db import models class Reporter(models.Model):
full_name = models.CharField(max_length=70) def __str__(self): # __unicode__ on Python 2
return self.full_name class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter) def __str__(self): # __unicode__ on Python 2
return self.headline

  这里建立了两个类,一个是Reporter,一个是Article。每个类都还定义了一个函数(Python中的函数相当于Java或者JavaScript中的方法,Python用关键字def对函数进行定义,JavaScript用function定义而已) "__str__" ,注意这里函数名字,是前后各有两个下划线,其作用就是返回这个类的字符串描述,可以理解成相当于java中的toString方法。

  Reporter有一个字段交full_name,类型是CharField(最大长度是70),这里我理解就是告诉程序他是一个字符串类型的数据,最大长度是70,方便根据此映射数据库。

  Article中定义了pub_date,他是一个时间类型的数据,headline是一个字符串类型的数据,content是一个text类型的数据,这里还给Article定义了一个外键ForeignKey为Reporter,这样在用程序自动生成数据库表的时候就会自动建立外键关联了。

  以上为Python对实体类的定义。然后通过执行Python命令就可以轻松创建数据库表了。

  自动创建数据库表的Python命令是:Python manage.py migrate  。其中migrate是迁移的意思,可以理解成将Python类迁移、映射到数据库中,Python会自动给表加上主键,名称是id。

  一旦建立了表,那么Python就可以通过Python中定义的类操作这些数据库中的表数据了。如下:

  

 # 导入刚才新建模块中的类Reporter和Article
>>> from news.models import Reporter, Article # 查询所有的Reporter,显示为空
>>> Reporter.objects.all()
[] # 建立一个新的Reporter,全称叫John Smith
>>> r = Reporter(full_name='John Smith') # 保存这个对象到数据库,只需要调用save函数即可。
>>> r.save() # 通过.id即可以获取到刚才保存的Reporter数据的id
>>> r.id
1 #再次查询数据库中的Reporter,则刚才新插入的Reporter会显示出来,可以看出来这里显示的内容即是在类里面__str__定义返回的内容
>>> Reporter.objects.all()
[<Reporter: John Smith>] # 通过.属性名称既可以获取属性名
>>> r.full_name
'John Smith' # django还提供了丰富的API来查询过滤数据,
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
#查询full_name以'John'开头的数据
>>> Reporter.objects.get(full_name__startswith='John')
<Reporter: John Smith>
  #传full_name中包含'mith'的数据
>>> Reporter.objects.get(full_name__contains='mith')
<Reporter: John Smith>
  #如果查询不到数据,则会报查询不到的异常。这个应该是可以通过设定来防止报错的?
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Reporter matching query does not exist. # 建立一个新的Article
>>> from datetime import date
>>> a = Article(pub_date=date.today(), headline='Django is cool',
... content='Yeah.', reporter=r)
>>> a.save() # Now the article is in the database.
>>> Article.objects.all()
[<Article: Django is cool>] # Article对象可以通过api获取其关联的Reporter对象的数据
>>> r = a.reporter
>>> r.full_name
'John Smith' # 反之亦然,通过Reporter对象可以获取所有的Article对象,通过对象.关联对象_set.all()获取
>>> r.article_set.all()
[<Article: Django is cool>] # The API follows relationships as far as you need, performing efficient
# JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with "John".
  # Article还可以通过过滤其所属Reporter的相关信息来查询自己,如下通过reporter__reporter中的属性__startswith='John'
  # 确实好强大  
>>> Article.objects.filter(reporter__full_name__startswith='John')
[<Article: Django is cool>] # Change an object by altering its attributes and calling save().
# 改变Reporter中full_name的值
>>> r.full_name = 'Billy Goat'
>>> r.save() # Delete an object with delete().
# 删除Reporter
>>> r.delete()