Intro to Django

"Basic Introduction"

Posted by Mugen on May 9, 2020

It took longer than expected.

Django Tutorial

Django Documentation

Django Tutorial Part 3: Using models

Django Tips #4 Automatic DateTime Fields

How to trigger function in Django app

Get inspiration from this link:

How to run function if model instance field is equal to inplay (Django)

Be clear about what method to use after reading this:

Trigger a function in a Django model every time its variables change

django signals

In fact, it already use created to denote new object, but I didn’t notice it back to that time, and searched other links to achieving only trigger on new objects.

Django: how can I tell if the post_save signal triggers on a new object?

There is a created named argument which will be set to True if it’s a new object.

This is the Documentation of Signals

More examples here

Django signal 信号机制的使用: 中文介绍

python 之 Django框架(APP和ORM的使用):中文介绍

理解Django的makemigrations和migrate

在你改动了 model.py的内容之后执行下面的命令:

1
python manage.py makemigrations

相当于在该app下建立 migrations目录,并记录下你所有的关于modes.py的改动,比如0001_initial.py, 但是这个改动还没有作用到数据库文件

你可以手动打开这个文件,看看里面是什么。当makemigrations之后产生了0001_initial.py 文件,你可以查看下该migrations会对应于什么样子的SQL命令,使用如下命令:

1
python manage.py sqlmigrate theapp 0001

在makemigrations之后执行命令:

1
python manage.py migrate

将该改动作用到数据库文件,比如产生table,修改字段的类型等。