猿问

Django - 跟踪评论

我正在构建一个网络应用程序,其中每个产品都有自己的“配置文件”。我需要向模型添加某种字段,我可以在其中添加带有日期和文本的“评论”,以跟踪信息,例如公式更改、提供商更改、价格更改等。


有任何想法吗?


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)

因此,对于发生的每个事件,我都需要一个带有文本字段中提供的描述的新入口。


qq_笑_17
浏览 314回答 2
2回答

慕雪6442864

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,您可以在您的HorseAdminclass HorseTrackerInline(admin.TabularInline):    model = HorseTrackerclass HorseAdmin(admin.ModelAdmin):    list_display = ['name', 'nacimiento', 'nro', 'event', 'slug', ]    inlines = [ HorseTrackerInline, ]

红糖糍粑

如果你想跟踪各种模型,我建议使用类似django-simple-history 的东西来跟踪模型中的变化。将history字段添加到模型可让您保存对字段所做的所有更改,然后访问历史记录。如果要添加自定义消息,可以将字段添加到历史模型,并在信号中设置消息。from simple_history.models import HistoricalRecordsclass MessageHistoricalModel(models.Model):&nbsp; &nbsp; """&nbsp; &nbsp; Abstract model for history models tracking custom message.&nbsp; &nbsp; """&nbsp; &nbsp; message = models.TextField(blank=True, null=True)&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; abstract = Trueclass Horse(models.Model):&nbsp; &nbsp; name = models.CharField(max_length=255)&nbsp; &nbsp; birthdate = models.DateField(blank=True, null=True)&nbsp; &nbsp; nro = models.IntegerField()&nbsp; &nbsp; event = models.TextField()&nbsp; &nbsp; slug = models.SlugField(unique=True)&nbsp; &nbsp; history = HistoricalRecords(bases=[MessageHistoricalModel,])然后使用信号,您可以使用diff获取更改,然后保存一条自定义消息,说明更改的是谁做出的。from django.dispatch import receiverfrom simple_history.signals import (post_create_historical_record)@receiver(post_create_historical_record)def post_create_historical_record_callback(sender, **kwargs):&nbsp; &nbsp; history_instance = kwargs['history_instance'] # the historical record created&nbsp; &nbsp; # <use diff to get the changed fields and create the message>&nbsp; &nbsp; history_instance.message = "your custom message"&nbsp; &nbsp; history_instance.save()您可以生成一个非常通用的信号,适用于使用“历史”字段跟踪的所有模型。注意:我将“nacimiento”重命名为“生日”,以保持用英语命名所有字段的一致性。
随时随地看视频慕课网APP

相关分类

Python
我要回答