【问题标题】:Django model history with foreign keys history tracking using django-simple-history使用 django-simple-history 跟踪具有外键历史记录的 Django 模型历史记录
【发布时间】:2020-10-10 05:14:39
【问题描述】:

我有三个具有历史记录的模型:

class WifiUser(models.Model):
    ....
    wifiDevice = models.OneToOneField(WifiDevice, on_delete=models.CASCADE, default=None)
    wifiSim = models.OneToOneField(WifiSim, on_delete=models.CASCADE, default=None)
    history = HistoricalRecords()

class WifiDevice(models.Model):
    ....
    history = HistoricalRecords()

class WifiSim(models.Model):
    ....
    history = HistoricalRecords()

我想用相应的外键历史记录来跟踪历史。但是当访问 Wifiuser 的历史时,我得到了 WifiDevice 和 WifiSim 的最新值。我希望 WifiDevice 和 WifiSim 的历史记录指向他们的记录。最好的方法是什么?

【问题讨论】:

  • 在您的相关模型实例中使用 SimpleHistory 提供的as_of() 方法

标签: django database django-models django-views django-templates


【解决方案1】:

为了跟踪历史而不是只显示最后一个对象,我建议您为历史添加一个模型,其中包含 wifiUser wifiDevice 和 wifiSim,并且可能为访问日期和时间添加一个日期,用于自动添加日期我建议你看看这个答案 (Django auto now and auto add now)

【讨论】:

  • 你好,我认为你的方法可能是要走的路。但是您如何建议使用外键为历史添加模型?因为外键将指向最新的对象。
  • 您将添加到数据库中,因此每个外键都将保存到其相应​​的对象中,并且拥有新的外键不会导致数据丢失,只要确保您没有一个唯一的共同属性,因为当用户可能使用多个设备时,这会导致完整性错误。
【解决方案2】:

我在 Upwork 看到你的帖子,你需要重写两个模型 WifiDevice 和 WifiSim 的 str 方法如下:


class WifiDevice(models.Model):
    ....
    history = HistoricalRecords()

    def __str__ (self):
    return self.history // the solution 




class WifiSim(models.Model):
    ....
    history = HistoricalRecords()
    def __str__ (self):
    return self.history // the solution 

【讨论】:

    【解决方案3】:
    class BilingualCorpus(models.Model):
        file_url = models.FileField(upload_to='corpus_files/', validators=[FileExtensionValidator(allowed_extensions=['txt', 'csv', 'tmx', 'xlsx'])])
        file_name = models.CharField(max_length=255, default='none')
        name = models.CharField(max_length=50,default='none')
        s_lang = models.CharField(max_length=5,default='en')
        t_lang = models.CharField(max_length=5,default='th')
        note = models.TextField(blank=True)
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        created_at = models.DateTimeField(auto_now_add=True, blank=True)
        updated_at = models.DateTimeField(auto_now=True, blank=True)
    
    class CorpusStatus(models.Model):
        status = models.CharField(max_length=50, default='Unchecked')
    
    class  BilingualSentence(models.Model):
        corpus = models.ForeignKey(BilingualCorpus, on_delete=models.CASCADE)
        source = models.TextField(blank=True)
        target = models.TextField(blank=True)
        status = models.ForeignKey(CorpusStatus, blank=True, null=True, on_delete=models.SET_NULL)
    

    【讨论】:

    • 您能解释一下这是如何解决问题的吗?请务必使用编辑按钮将解释直接添加到您的答案中,而不是将其留在 cmets 中。
    猜你喜欢
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    相关资源
    最近更新 更多