【问题标题】:django multi-table inheritance validation with the admin app使用管理应用程序验证 django 多表继承
【发布时间】:2019-10-31 00:11:48
【问题描述】:

使用文档中的multi-table inheritance 设置的 Django 模型时,如果存在匹配的“地点”条目,则管理应用程序无法添加新的“餐厅”模型 - 管理应用程序返回“具有此名称的地点”已经存在”。

Django 的ModelForm 提供表单验证方法,Model 提供唯一性验证。
将现有的 Place 入口变成餐厅的最佳地点是哪个?
你会怎么做呢?

例如,Place(name="hotdogshop", address="bond street") 存在,用户尝试添加 Restaraunt( serving_hot_dogs=True, serving_pizza=False, name="hotdogshop", address="邦德街”)。期望的最终结果与我们一开始就将“hotdogshop”添加为“Restaraunt”一样。

【问题讨论】:

标签: django django-models django-forms django-admin django-orm


【解决方案1】:

最初的解决方法是在模型验证中插入额外的唯一性检查,然后改用django-typed-models,以便我们可以重铸模型。

例如,将以下伪代码添加到您的模型中。

def _perform_unique_checks(self, unique_checks):

    print("Performing custom Recast Unique Check")

    try:
        # Search for any existing Model you want to replace.
        exists = MyModel.objects.get(...)
        if exists:
            # django-typed-models can be recast without affecting integrity.
            exist.recast('myApp.mySubclassedModel')
            # Pretend nothing went wrong, so the rest of the save process continues.
            return {}

    except TwitterHarvestedUser.DoesNotExist:
        pass

    return super()._perform_unique_checks(unique_checks)

注意如何合并旧模型和新模型中的数据。默认情况下,Django 的 save() 方法最终会替换所有旧模型字段,即使它们在新模型中没有更改。

这不适用于 MyModel.objects.create()

【讨论】:

    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多