python应用的方方面面-0-Django
model 的继承
- 抽象继承
1 | class Animal(models.Model): |
class Country(models.Model):
name = models.CharField(max_length=10)
#...
class Province(Country):
return = models.BooleanField()
#...
1 |
|
from django.contrib.auth.models import User
class Person(User):
# this makes a class proxy
proxy = True
def can_dance(self):
return True
both Yellow and Black can_dance :)
class Yellow(Person):
hometown = models.CharField(max_length=30)
class Black(Person)
tribe_name = models.CharField(max_length=100)
1 |
|
可以改写为
1 | from django.db.models import Q |
验证表单提交格式是否正确 使用哪个函数?
is_valid() # 函数方法,用于检查表单提交是否正确
取消级连删除
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
并且SET_NULL只有在null为True的时候,才可以使用
django 在 model 保存前做一定的固定操作
1 |
|
django session
说到session的运行机制,就一定要先说一下cookie这一段信息。一般情况下cookies都是我们的浏览器生成的(显然可以人为修改),用于服务器对户进行筛选和维护,但是这个听上去很好吃的东西,能存的东西有点少而且容易被别人利用。这时候基于cookies的session的意义就比较明显了,在客户端的cookies中我们只保存session id,而将完整信息以加密信息的形式保存到服务器端,这样服务器可以根据session id相对安全的在数据库中查询用户的更细致的信息和状态。
在Django中session和cookies的操作方法一样,如下:
1 |
|