添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

上一篇博客 : 理解Django的通用外键 -> GenericForeignKey, GenericRelation

什么是Timeline设计?

很多博客与问答网站,首页内容都是来自不同模块,让不同模块的内容在首页实现发表时间顺序排列,就是Timeline设计

ps : 大型公司都有用户画像系统与推荐算法,并不适用Timeline设计

使用contenttype,使不同模块内容按照时间顺序排列

假设现在有模块,想让内容按照时间顺序排列:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class News(models.Model):
    """动态"""
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
class Article(models.Model):
    """文章"""
    title = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
class Question(models.Model):
    """问题"""
    q_title = models.CharField(max_length=255)
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)

使用ContentType 建立通用模型类

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class Index(models.Model):
	"""通用模型类"""
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    pub_date = models.DateField()  # 当前时间
    class Meta:
        ording = [-"pub_date"]
class News(models.Model):
    """动态"""
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
    # 通用关联到Index
    index = GenericRelation(Index)
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 表生成数据时,在Index表生成一条数据, 时间为 此记录提交时间
        self.index.get_or_create(pub_date=self.pub_date)
class Article(models.Model):
    """文章"""
    title = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
    # 通用关联到Index
    index = GenericRelation(Index)
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 表生成数据时,在Index表生成一条数据, 时间为 此记录提交时间
        self.index.get_or_create(pub_date=self.pub_date)
class Question(models.Model):
    """问题"""
    q_title = models.CharField(max_length=255)
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
    # 通用关联到Index
    index = GenericRelation(Index)
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 表生成数据时,在Index表生成一条数据, 时间为 此记录提交时间
        self.index.get_or_create(pub_date=self.pub_date)

这样就可以通过Index来查询其他三个模型类的数据,然后根据 ording 来倒叙排列

不使用GenericRelation关联到Index
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
class Index(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    pub_date = models.DateField()  # 当前时间
    class Meta:
        ording = [-"pub_date"]
class News(models.Model):
    """动态"""
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 使用ContentType.objects.get_for_mode 查询当前class object 属于 那一应用(app_label)的 模型类(models)
        ct = ContentType.objects.get_for_model(self)
        # 指定content_type 与object_id (self.id 为 当前模型类主键)
        self.index.get_or_create(content_type=ct, object_id=self.id,
                                 pub_date=self.pub_date)
class Article(models.Model):
    """文章"""
    title = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 使用ContentType.objects.get_for_mode 查询当前class object 属于 那一应用(app_label)的 模型类(models)
        ct = ContentType.objects.get_for_model(self)
        # 指定content_type 与object_id (self.id 为 当前模型类主键)
        self.index.get_or_create(content_type=ct, object_id=self.id,
                                 pub_date=self.pub_date)
class Question(models.Model):
    """问题"""
    q_title = models.CharField(max_length=255)
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        # 使用ContentType.objects.get_for_mode 查询当前class object 属于 那一应用(app_label)的 模型类(models)
        ct = ContentType.objects.get_for_model(self)
        # 指定content_type 与object_id (self.id 为 当前模型类主键)
        self.index.get_or_create(content_type=ct, object_id=self.id,
                                 pub_date=self.pub_date)

使用信号量,提高代码复用性

save()为每次模型类保存时,都要执行的操作,正好使用信号量机制
官方文档: https://docs.djangoproject.com/zh-hans/2.2/topics/signals/

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
class Index(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    pub_date = models.DateField()  # 当前时间
    class Meta:
        ording = [-"pub_date"]
class News(models.Model):
    """动态"""
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
class Article(models.Model):
    """文章"""
    title = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
class Question(models.Model):
    """问题"""
    q_title = models.CharField(max_length=255)
    content = models.CharField(max_length=255)
    pub_date = models.DateTimeField(auto_now_add=True)
def create_index(sender, instance, **kwargs):
    sender : 发送者
    instance : 模型类对象
    if "created" in kwargs:  # 模型类创建数据时执行created方法
        # 使用ContentType.objects.get_for_mode 查询当前class object 属于 那一应用(app_label)的 模型类(models)
        ct = ContentType.objects.get_for_model(instance)
        # 指定content_type 与 object_id
        Index.objects.get_or_create(content_type=ct, object_id=instance.id,
                                    pub_date=instance.pub_date)
post_save.connect(create_index, sender=News)  # 固定写法 接收函数
post_save.connect(create_index, sender=Article)
post_save.connect(create_index, sender=Question)
 

此处内容来自博客 : https://www.cnblogs.com/liwenzhou/p/9745331.html#autoid-2-1-2

django.db.models.signals.post_save 带有此信号的参数:
sender -> 模型类。
instance -> 正在保存的实际实例。
created -> 一个布尔值True如果创建了新记录。
raw -> 一个布尔值True如果模型按照显示的方式保存(即当加载固定装置时)。 不应该查询/修改数据库中的其他记录,因为数据库可能尚未处于一致状态。
using -> 正在使用的数据库别名。
update_fields -> 如果有字段被传递给Model.save()方法那么就是所传递的字段集,否则就是None。

使用Index表获取其他表记录
eg : 在前端使用Index获得文章表的title
假设 传递给前端上下文名字为 indexs
使用 indexs.content_object.title

进一步可以封装为方法:

class Index(models.Model):
	...
    @property
    def content(self):
        return self.content_object.title

相应的前端调用方法为: 上下文名字.content, 即可获得数据

上一篇博客 : 理解Django的通用外键 -> GenericForeignKey, GenericRelation什么是Timeline设计?很多博客与问答网站,首页内容都是来自不同模块,让不同模块的内容在首页实现发表时间顺序排列,就是Timeline设计ps : 大型公司都有用户画像系统与推荐算法,并不适用Timeline设计使用contenttype,使不同模块内容按照时...
django-admin-timeline 适用于Django管理员的类似Facebook的时间轴应用程序。 它与内置功能“每日进度”非常相似,但具有更好的模板和无限滚动。 动作按天细分,然后按动作分解。 可以按用户(多项选择)和内容类型(多项选择)过滤操作。 从django-admin-timeline 1.8开始: Django 2.2、3.0和3.1 Python 3.6、3.7和3.8 过去,从1.7.x版开始, django-admin-timeline仍可用于: Django 1.11、2.0 Python 2.7、3.5 在您的虚拟环境安装 来自PyPI的最新稳定版本: pip install django-admin-timeline BitBucket的最新稳定版本: pip install https://bitbuck
text = '需要加密的文本' hash_object = hashlib.sha256(text.encode()) hex_dig = hash_object.hexdigest() 其,`text`为需要加密的文本,`hashlib.sha256()`表示使用sha-256算法生成摘要,`hexdigest()`方法则将摘要转换成16进制字符串的形式。 3.将摘要存储到数据库或者进行其他操作 可以将`hex_dig`存储到数据库,或者进行其他操作,例如验证密码等。 需要注意的是,如果在Django用于存储密码,应该使用更安全的密码散列算法,例如bcrypt或者PBKDF2。