django与管理应用程序的多表继承验证

时间:2019-06-17 11:45:10

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

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

Django的ModelForm提供了表单验证方法,而Model提供了唯一性验证。
哪个地方可以将现有的Place条目转换为Restaurant?
你会怎么做?

例如,存在一个Place(name =“ hotdogshop”,address =“ bond street”),并且用户尝试添加餐厅(restaurant(serve_hot_dogs = True,serve_pizza = False,name =“ hotdogshop”,address =“邦德街”)。所需的最终结果将与我们最初添加“ hotdogshop”作为“ Restaraunt”一样。

1 个答案:

答案 0 :(得分:0)

最初的黑客解决方法是在模型验证中插入额外的唯一性检查,然后切换为使用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()