在Django中,如果你想要跟踪模型字段的历史变化,并且这些字段涉及到外键关系,你可以使用django-simple-history
库来实现这一功能。以下是如何将外键添加到Django字段历史中的步骤:
HistoricalRecords()
已正确添加到模型中,并且已经执行了迁移。# models.py
from django.db import models
from simple_history.models import HistoricalRecords
class Category(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
history = HistoricalRecords()
# 在视图或其他地方访问历史记录
article = Article.objects.get(id=1)
for history in article.history.all():
print(f"Title: {history.title}, Category ID: {history.category_id}")
通过以上步骤,你可以有效地将外键添加到Django字段历史中,并跟踪其变化。
领取专属 10元无门槛券
手把手带您无忧上云