You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用django-simple-history与django-computedfields时迁移冲突问题

问题:django-computedfields与django-simple-history迁移冲突

在Django应用中,使用django-computedfields实现带计算字段的模型后,添加django-simple-history记录历史版本,执行迁移时出现以下错误:

computedfields.resolver.ResolverException: <class 'arbolsaf.models.HistoricalSpeciesModel'> is not a subclass of ComputedFieldsModel

模型代码(简化版):

from computedfields.models import ComputedFieldsModel, computed, compute
from simple_history.models import HistoricalRecords

class SpeciesModel(BasicAuditModel, ComputedFieldsModel):

    history = HistoricalRecords()
    
    VALUES_CHOICES = (
        ("ninguno", "Ninguno"),
        ("bajo", "Bajo"),
        ("medio", "Medio"),
        ("alto", "Alto"),
    )
        
    cod_esp = models.CharField(_("Código especie"), max_length=50, unique=True)
    taxonid_wfo = models.CharField(_("Taxon ID WFO"), max_length=50)
    nombre_comun = models.CharField(_("Nombre común"), max_length=255)
    nombre_cientifico = models.CharField(_("Nombre científico"), max_length=255)
    nombre_cientifico_completo = models.CharField(_("Nombre científico completo"), max_length=255)
    familia = models.ForeignKey("arbolsaf.FamilyModel", verbose_name=_("Familia"), on_delete=models.RESTRICT)
    genero = models.ForeignKey("arbolsaf.GenderModel", verbose_name=_("Género"), on_delete=models.RESTRICT)
    epiteto = models.CharField(_("Epíteto"), max_length=50)
    
    variedad_subespecie = models.CharField(_("Variedad/Subespecie"), max_length=50, blank=True, null=True)
    autor = models.CharField(_("Autor"), max_length=255, blank=True, null=True)

    nativa = models.BooleanField(_("Nativa?"))

    class Meta:
        db_table = 'arbolsaf_species'
        managed = True
        ordering = ["nombre_cientifico"]
        verbose_name = 'Especie'
        verbose_name_plural = 'Especies'

解决方法

方法1:排除历史模型被computedfields检测

在项目的settings.py中添加配置,让django-computedfields忽略自动生成的历史模型:

COMPUTEDFIELDS_EXCLUDED_MODELS = [
    'arbolsaf.HistoricalSpeciesModel',
    # 如有其他冲突的历史模型,也一并添加
]

方法2:自定义历史模型并继承ComputedFieldsModel

如果需要历史模型也包含计算字段,可以自定义历史模型,让它继承ComputedFieldsModel和django-simple-history的HistoricalModel:

from computedfields.models import ComputedFieldsModel
from simple_history.models import HistoricalRecords, HistoricalModel

# 自定义历史模型
class HistoricalSpeciesModel(ComputedFieldsModel, HistoricalModel):
    class Meta:
        proxy = True
        verbose_name = 'Historial de Especie'
        verbose_name_plural = 'Historiales de Especies'

class SpeciesModel(BasicAuditModel, ComputedFieldsModel):
    # 指定使用自定义的历史模型
    history = HistoricalRecords(model=HistoricalSpeciesModel)
    
    # 其余字段和Meta信息保持不变
    # ...

执行以上修改后,重新生成并应用迁移即可解决冲突。

内容的提问来源于stack exchange,提问作者Ernesto Ruiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:47:37