日期:2014-05-16  浏览次数:20623 次

python数据库模型总结
先看一下数据库模型之间的对应关系:
Author      n:n      Book      n:1      Publisher
然后看看在python项目中的models.py中如何表示:
class Publisher(models.Model): 
    name = models.CharField(max_length=30) 
    address = models.CharField(max_length=50) 
    city = models.CharField(max_length=60) 
    state_province = models.CharField(max_length=30) 
    country = models.CharField(max_length=50) 
    website = models.URLField() 

class Author(models.Model): 
    first_name = models.CharField(max_length=30) 
    last_name = models.CharField(max_length=40) 
    email = models.EmailField(blank=True,verbose_name='e-mail') 

class Book(models.Model): 
    title = models.CharField(max_length=100) 
    authors = models.ManyToManyField(Author) 
    publisher = models.ForeignKey(Publisher) 
    publication_date = models.DateField(blank=True, null=True) 

下面看看如何插入数据:
方法一:
p1 = Publisher(name='Addison-Wesley', address='75 Arlington Street',city='Boston', state_province='MA', country='U.S.A.',website='http://www.apress.com/') 
p1.save() 

方法二:
p1 = Publisher.objects.create(name='Apress',address='2855 Telegraph Avenue',city='Berkeley', state_province='CA', country='U.S.A.',website='http://www.apress.com/') 

更新数据:
方法一:
p1.name = 'Apress Publishing' 
p1.save() 

方法二:
Publisher.objects.filter(id=1).update(name='Apress Publishing') 


[color=red]注意:
第一种方法更新数据库中所有的字段,
生成数据库语句是:
UPDATE book_publisher SET 
     name = 'Apress Publishing', 
     address = '2855 Telegraph Ave.', 
    city = 'Berkeley', 
     state_province = 'CA', 
     country = 'U.S.A.', 
     website = 'http://www.apress.com' 
 WHERE id = 52; 


第二种数据库语句是:
UPDATE books_publisher 
SET name = 'Apress Publishing' 
WHERE id = 52; 
[/color]

更新所有记录
Publisher.objects.all().update(country='USA') 


下面是选择对象:
Publisher.objects.all() 选择所有 
Publisher.objects.filter(name= ‘ Apress ’ ) 数据过滤 
Publisher.objects.filter(name__contains="press") 
Publisher.objects.get(name= “ Apress ” ) 获取单个对象



注意: filter()`` 函数返回一个记录集,这个记录集是一个列表 QuerySet 。相对列表来说,有些时候我们更需要获取单个的对 象, 用 `` get()`` 方法。
Get ()方法:
如果结果是多个对象,会导致抛出异常;
如果查询没有返回结果也会抛出异常。

contains转换成数据库语句是like



下面是删除对象:
p = Publisher.objects.get(name="dddddddddddd") 
p.delete() 

或者
Publisher.objects.filter(country='USA').delete() 
Publisher.objects.all().delete() 


下面是访问外键---一对多访问:
b = Book.objects.get(id= 1 ) 
b.publisher 
b.publisher.website 

访问外键---多对一访问:
p = Publisher.objects.get(name='Apress Publishing') 
p.book_set.all() 
p.book_set.filter(name__icontains='django') 

访问外键---多对多访问:
b = Book.objects.get(id= 2 ) 
b.authors.all() 
b.authors.filter(first_name='Adrian') 
b.authors.filter(first_name='Adam') 

访问外键---多对多访问(反向):