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

  

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

 1 mysite/news/models.py
 2 from django.db import models
 3 
 4 class Reporter(models.Model):
 5     full_name = models.CharField(max_length=70)
 6 
 7     def __str__(self):              # __unicode__ on Python 2
 8         return self.full_name
 9 
10 class Article(models.Model):
11     pub_date = models.DateField()
12     headline = models.CharField(max_length=200)
13     content = models.TextField()
14     reporter = models.ForeignKey(Reporter)
15 
16     def __str__(self):              # __unicode__ on Python 2
17         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中定义的类操作这些数据库中的表数据了。如下:

  

 1 # 导入刚才新建模块中的类Reporter和Article
 2 >>> from news.models import Reporter, Article
 3 
 4 # 查询所有的Reporter,显示为空
 5 >>> Reporter.objects.all()
 6 []
 7 
 8 # 建立一个新的Reporter,全称叫John Smith
 9 >>> r = Reporter(full_name='John Smith')
10 
11 # 保存这个对象到数据库,只需要调用save函数即可。
12 >>> r.save()
13 
14 # 通过.id即可以获取到刚才保存的Reporter数据的id
15 >>> r.id
16 1
17 
18 #再次查询数据库中的Reporter,则刚才新插入的Reporter会显示出来,可以看出来这里显示的内容即是在类里面__str__定义返回的内容
19 >>> Reporter.objects.all()
20 [<Reporter: John Smith>]
21 
22 # 通过.属性名称既可以获取属性名
23 >>> r.full_name
24 'John Smith'
25 
26 # django还提供了丰富的API来查询过滤数据,
27 >>> Reporter.objects.get(id=1)
28 <Reporter: John Smith>
#查询full_name以'John'开头的数据 29 >>> Reporter.objects.get(full_name__startswith='John') 30 <Reporter: John Smith>
  #传full_name中包含'mith'的数据 31 >>> Reporter.objects.get(full_name__contains='mith') 32 <Reporter: John Smith>
  #如果查询不到数据,则会报查询不到的异常。这个应该是可以通过设定来防止报错的? 33 >>> Reporter.objects.get(id=2) 34 Traceback (most recent call last): 35 ... 36 DoesNotExist: Reporter matching query does not exist. 37 38 # 建立一个新的Article 39 >>> from datetime import date 40 >>> a = Article(pub_date=date.today(), headline='Django is cool', 41 ... content='Yeah.', reporter=r) 42 >>> a.save() 43 44 # Now the article is in the database. 45 >>> Article.objects.all() 46 [<Article: Django is cool>] 47 48 # Article对象可以通过api获取其关联的Reporter对象的数据 49 >>> r = a.reporter 50 >>> r.full_name 51 'John Smith' 52 53 # 反之亦然,通过Reporter对象可以获取所有的Article对象,通过对象.关联对象_set.all()获取 54 >>> r.article_set.all() 55 [<Article: Django is cool>] 56 57 # The API follows relationships as far as you need, performing efficient 58 # JOINs for you behind the scenes. 59 # This finds all articles by a reporter whose name starts with "John".
  # Article还可以通过过滤其所属Reporter的相关信息来查询自己,如下通过reporter__reporter中的属性__startswith='John'
  # 确实好强大   60 >>> Article.objects.filter(reporter__full_name__startswith='John') 61 [<Article: Django is cool>] 62 63 # Change an object by altering its attributes and calling save().
# 改变Reporter中full_name的值
64 >>> r.full_name = 'Billy Goat' 65 >>> r.save() 66 67 # Delete an object with delete().
# 删除Reporter
68 >>> r.delete()

 


posted @ 2015-05-27 15:38  nihousheng  阅读(433)  评论(0编辑  收藏  举报