Django学习笔记3

1.部署Django到服务器后,进入Admin出现'WSGIRequest' object has no attribute 'user'的错误。

查了之后,原来我服务器用的是1.9,本机开发环境1.10
settings中的中间件格式1.9为MIDDLEWARE_CLASSES=[],1.10为MIDDLEWARE=[].
里面中间件的书写顺序也有不一样,还不是太了解,现按默认的来吧。

2.Verbose field names

ForeignKey,ManyToManyField,OneToOneField这三个field类型之外,field的第一个参数,是设置verbose_name,如:

first_name = models.CharField("person's first name",max_length=30)

不设置第一个参数,verbose_name自动将下划线换为空格,即:first name

ForeignKey,OneToOneField,设置verbose_name时,必须使用关键字参数

poll = models.ForeignKey(
    Poll,on_delete=models.CASCADE,verbose_name="the related poll",)

其他field类型也可以如此使用。

3.ForeignKey.on_delete

on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

on_delete在2.0之后将是必选参数。2.0之前是可选,默认值为CASCADE.

CASCADE: 默认值,model对象会和ForeignKey关联对象一起被删除
SET_NULL:将model对象的ForeignKey字段设为null。当然需要将null设为True。
SET_DEFAULT:将model对象的ForeignKey字段设为默认值。
Protect:删除ForeignKey关联对象时会生成一个ProtectedError,这样ForeignKey关联对象就不会被删除了。
SET():将model对象的ForeignKey字段设为传递给SET()的值。

4.DateField和DateTimeField的两个可选参数auto_newauto_new_add

auto_now,自动设置更新时间

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(),though you can specify a custom value for the field in an update like that.

auto_now将会在调用Model.save()是自动生效,在调用QuerySet.update()时不生效
(注:save()和update()都会更新数据库,执行SQL语句不同,update一般用于批量更新数据)

auto_now_add,自动设置创建时间
自动第一次创建时填充的时间

DateField和DateTimeField分别调用日期和时间的函数

For DateField: default=date.today - from datetime.date.today()
For DateTimeField: default=timezone.now - from django.utils.timezone.now()

相关文章

注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有...
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供...
一、Django介绍Python下有许多款不同的 Web 框架。Django是重...
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小...
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的...