码迷,mamicode.com
首页 > 其他好文 > 详细

django1.8读书笔记模型高级进阶

时间:2016-05-01 23:04:27      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

一、访问外键和多对多值

例如:模型类定义如下

技术分享
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
View Code

在定义外键或者多对多的类中访问外键比较方便。直接获得一条数据对象,然后通过外键访问外键关联的对象。

如果想要追溯回来,也可以实现。需要使用_set.all()来获取。使用类名的小写形式。比如

>>> a = Author.objects.get(first_name=Adrian, last_name=Holovaty)
>>> a.book_set.all()
[<Book: The Django Book>, <Book: Adrians Other Book>]

二、manager是一个对象,django通过它进行数据库查询,每个Django模块至少有一个manager,可以创建自定义manager以定制数据库访问。为模块添加表级功能的首选方法。

 需要修改的是

在模型中添加objects属性为继承的manager类,在类中添加新方法即可,不要添加初始函数。

三、执行原始SQL

通过django.db.connection可以实现执行原始SQL语句,通过connection.cursor()得到一个游标对像,通过cursor.execute(sql, [params])来执行SQL语句,通过cursor.fetchone()或者cursor.fetchall()来返回记录集。

>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute("""
...    SELECT DISTINCT first_name
...    FROM people_person
...    WHERE last_name = %s""", [‘Lennon‘])
>>> row = cursor.fetchone()
>>> print row
[John]

说明:将执行的原始SQL语句放在定制的MANAGER或者模型中比较好。

from django.db import connection, models

class PersonManager(models.Manager):
    def first_names(self, last_name):
        cursor = connection.cursor()
        cursor.execute("""
            SELECT DISTINCT first_name
            FROM people_person
            WHERE last_name = %s""", [last_name])
        return [row[0] for row in cursor.fetchone()]

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    objects = PersonManager()
>>> Person.objects.first_names(Lennon)
[John, Cynthia]

 

django1.8读书笔记模型高级进阶

标签:

原文地址:http://www.cnblogs.com/zhaopengcheng/p/5451295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!