Django:动态模型在创建后消失 [英] Django: dynamic models disappear after creation

查看:79
本文介绍了Django:动态模型在创建后消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有2个模型。 Model_A和Model_B。

Let's say I have 2 models. Model_A and Model_B.

每当管理员用户对model_A对象进行更改时,他们都会单击保存按钮。

Whenever the admin user makes a change to an object of model_A, they click the "save" button.

因此,当发生保存时,我想发送一个post_save信号,该信号创建一个继承自Model_B的模型。

So, when a "save" happens, I would like to send a post_save signal that creates a model that inherits from Model_B.

当我像下面这样进行操作时,确实创建了模型,但是刷新页面后它们消失了,有时刷新后它们又出现了。但是他们并不总是排在榜单上。 (很奇怪,我知道!)

When I do so like the following, the models do get created but they disappear after refreshing the page, and sometimes they appear again after refreshing again. But they don't always stay on the list. (Weird, I know!)

所以post_save信号的代码如下:

So the code for the post_save signal is like so:

post_save.connect(create_new_model, sender=Model_A)

我的create_new_model就像因此:

My create_new_model is like so:

def create_new_model(sender, instance, **kwargs):
    attrs = {
        'field1': models.CharField(max_length=40),
        'field2': models.CharField(max_length=40),
        '__module__': 'appname.models'
    }

    from appname.models import create_model, admin_options, modelsList

    mod = create_model(name=str(len(modelsList)),
                       fields=attrs,
                       admin_opts=admin_options
                       )
    modelsList.append(mod)

最后,创建动态模型(create_model)的函数如下所示:

And finally, the function that creates the dynamic models (create_model) is like so:

def create_model(name, fields=None, admin_opts=None):

    from appname.models import Model_A

    attrs = fields

    model = type(name, (Model_A,), attrs)

    if admin_opts is not None:
        admin.site.register(model, admin_opts)

    return model

有人知道为什么会发生这种偷偷摸摸的事情吗?

Does anyone know why this sneaky thing might be happening?

推荐答案

这大概是因为您的服务器正在使用多个过程。任何动态类都只会存在于创建它的过程中。

This is presumably happening because your server is using more than one process. Any dynamic class will only exist within the process that creates it; and even then it won't persist across process restarts.

我不知道您的用例在这里,但肯定不是这样做的方法。

I don't know what your use case is here but this is certainly not the way to do it.

这篇关于Django:动态模型在创建后消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆