一、访问外键和多对多值
例如:模型类定义如下
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
在定义外键或者多对多的类中访问外键比较方便。直接获得一条数据对象,然后通过外键访问外键关联的对象。
如果想要追溯回来,也可以实现。需要使用_set.all()来获取。使用类名的小写形式。比如
>>> a = Author.objects.get(first_name='Adrian', last_name='Holovaty') >>> a.book_set.all() [<Book: The Django Book>, <Book: Adrian's 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']
四、为有外键的表插入数据
django中和sql执行的有点不太一样,在sql中对有外键的表插入数据,在外键字段直接插入对应的外键值即可。在django中需要插入对应的数据对象。
class UserInfo(models.Model): username = models.CharField(max_length=30); password = models.CharField(max_length=15); class LogInfo(models.Model): user = models.ForeignKey(UserInfo); timestamp = models.DateTimeField(auto_now_add = True);
django中向loginfo插入数据
u1 = UserInfo.objects.get(username='lisi') LogInfo.objects.create(user=u1)