1、泛型外鍵
通過content_type,object_id,GenericForeignKey三個字段定義任意外鍵,ContentType是Django裏面自帶的所有模型的元表(關鍵字是app_label和model),
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.db.models import signals
class UserAction(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(verbose_name="標識")
action = GenericForeignKey('content_type', 'object_id')
add_time = models.DateTimeField(auto_now_add=True, verbose_name='添加時間',null=True)
def __str__(self):
return self.user.username+":"+self.action.name
def save(sender, instance, signal, *args, **kwargs):
action = UserAction(action=instance)
action.save()
signals.post_save.connect(save, sender=UserProfile)
在django中,操作模型可以產生signals,通過註冊回調函數來實現監聽觸發後的動作,比如上面的新建模型實例,保存到數據庫,常用的有pre_save,post_save,pre_delete,post_delete,m2m_changed,request_started,request_finished。