mooc在线教育网开发流程总结(六)其他核心功能

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。

猜你喜欢

转载自blog.csdn.net/sf131097/article/details/80101055
今日推荐