首页 > 解决方案 > 具有动态虚拟字段的 Django 代理模型

问题描述

我们将数据存储在“真实”模型字段和定义并存储在 JSON 结构中的字段的混合中。为了简化使用我们的模型序列化程序和 DRF 处理这些结构,我们考虑实现一个代理模型,该模型查找动态字段的结构/数据并将这些字段添加到代理模型

class Classification(AbstractContent):
    """ classification model """

    name = models.CharField(
        verbose_name=_('name'),
        max_length=255,
        null=False,
        blank=False,
    )
    # for example we have like that in our structure
    #{'topEntry': {type:'bool',value:'false'}, 'addName': {type:'string, value: 'test}
    dynamic = models.JSONSchemaField(content_type=None, null=True)

我们现在想要得到一个代理模型,它由那些真实的模型字段(本例中的名称)+两个附加字段“topEntry”和“addName”组成。使用@property 在代理模型中添加这些字段对我们来说没有问题,但是尝试其他方式序列化程序将无法识别我们的字段。

标签: jsondjangodynamicproxymodel

解决方案


推荐阅读