在 Django 中完成文本的完整历史记录,可以通过以下几个步骤实现:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class History(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
current_text = models.TextField()
from django.db.models.signals import pre_save
from django.dispatch import receiver
@receiver(pre_save, sender=MyModel)
def create_history(sender, instance, **kwargs):
if instance.pk:
old_instance = MyModel.objects.get(pk=instance.pk)
if old_instance.current_text != instance.current_text:
History.objects.create(
content_object=instance,
text=old_instance.current_text
)
my_model_instance = MyModel.objects.get(id=1)
histories = History.objects.filter(content_object=my_model_instance).order_by('-created_at')
这样,在 Django 中就可以实现文本的完整历史记录功能了。
领取专属 10元无门槛券
手把手带您无忧上云