2 回答

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, ]

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”重命名为“生日”,以保持用英语命名所有字段的一致性。
添加回答
举报