为了账号安全,请及时绑定邮箱和手机立即绑定

Django - 跟踪评论

Django - 跟踪评论

qq_笑_17 2021-11-23 16:39:36
我正在构建一个网络应用程序,其中每个产品都有自己的“配置文件”。我需要向模型添加某种字段,我可以在其中添加带有日期和文本的“评论”,以跟踪信息,例如公式更改、提供商更改、价格更改等。有任何想法吗?models.py    from django.db import models# Create your models here.class Horse(models.Model):    name = models.CharField(max_length=255)    nacimiento = models.DateField(blank=True, null=True)    nro = models.IntegerField()    event = models.TextField()    slug = models.SlugField(unique=True)    def __str__(self):        return '%s-%s' % (self.name, self.nro)因此,对于发生的每个事件,我都需要一个带有文本字段中提供的描述的新入口。
查看完整描述

2 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

class HorseTracker(models.Model):

    horse = models.ForeignKey(Horse, on_delete=models.CASCADE, related_name='horse')

    comment = models.CharField(max_length=128)

    created_at = models.DateTimeField(auto_now_add=True)


    class Meta:

        ordering = ['-created_at']

每次更改模型中的某些内容时,您都可以创建新实例,HorseTracker并描述您所做的更改。


为了使它更有用TabularInline,您可以在您的HorseAdmin


class HorseTrackerInline(admin.TabularInline):

    model = HorseTracker


class HorseAdmin(admin.ModelAdmin):

    list_display = ['name', 'nacimiento', 'nro', 'event', 'slug', ]

    inlines = [ HorseTrackerInline, ]


查看完整回答
反对 回复 2021-11-23
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

如果你想跟踪各种模型,我建议使用类似django-simple-history 的东西来跟踪模型中的变化。


将history字段添加到模型可让您保存对字段所做的所有更改,然后访问历史记录。如果要添加自定义消息,可以将字段添加到历史模型,并在信号中设置消息。


from simple_history.models import HistoricalRecords


class MessageHistoricalModel(models.Model):

    """

    Abstract model for history models tracking custom message.

    """

    message = models.TextField(blank=True, null=True)


    class Meta:

        abstract = True


class Horse(models.Model):

    name = models.CharField(max_length=255)

    birthdate = models.DateField(blank=True, null=True)

    nro = models.IntegerField()

    event = models.TextField()

    slug = models.SlugField(unique=True)


    history = HistoricalRecords(bases=[MessageHistoricalModel,])

然后使用信号,您可以使用diff获取更改,然后保存一条自定义消息,说明更改的是谁做出的。


from django.dispatch import receiver

from simple_history.signals import (post_create_historical_record)


@receiver(post_create_historical_record)

def post_create_historical_record_callback(sender, **kwargs):

    history_instance = kwargs['history_instance'] # the historical record created


    # <use diff to get the changed fields and create the message>


    history_instance.message = "your custom message"

    history_instance.save()

您可以生成一个非常通用的信号,适用于使用“历史”字段跟踪的所有模型。


注意:我将“nacimiento”重命名为“生日”,以保持用英语命名所有字段的一致性。


查看完整回答
反对 回复 2021-11-23
  • 2 回答
  • 0 关注
  • 313 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信