django 模型高级用法

from django.db import models

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()

    def __unicode__(self):
        return self.name

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

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

    def __unicode__(self):
        return self.title

1 外键 高级用法

正常用法: b = Book.object.all() 拿到全部
拿到某个值 b = Book.object.get(id = 50)
那么拿到这个书的出版商: b.publisher 就可以 

那么反向通过出版商找书籍呢? easy
p = publisher.object.get(name = leisen media)
p.book_set.all 就能拿到这个出版商出的书
你可以对其进行分割  p.book_ser.filter(price__gt=100)
p.book_set.filter(name__icontains='django')  

2 多对多的用法和外键一样

[3 模型自定义函数,可以把一些常用的查询写成函数][1]

class BookManager(models.Manager):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()