如何在Django中创建动态模型?

时间:2019-11-19 06:25:45

标签: django django-models django-views

如何在Django中创建动态模型? 在这里,我尝试使用CreateDynamicModel创建动态模型,但未创建模型和管理界面。

    def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):

        class Meta:
            pass

        if app_label:
            setattr(Meta, 'app_label', app_label)

        if options is not None:
            for key, value in options.iteritems():
                setattr(Meta, key, value)

        # Set up a dictionary to simulate declarations within a class

        attrs = {

            '__module__': 'myapp.models'
         }


        # Add in any fields that were provided
        if fields:
            attrs.update(fields)

        # Create the class, which automatically triggers ModelBase processing
        model = type(name, (models.Model,), attrs)
        from django.core.management import sql, color
        from django.db import connection

        # Standard syncdb expects models to be in reliable locations,
        # so dynamic models need to bypass django.core.management.syncdb.
        # On the plus side, this allows individual models to be installed
        # without installing the entire project structure.
        # On the other hand, this means that things like relationships and
        # indexes will have to be handled manually.
        # This installs only the basic table definition.

        # disable terminal colors in the sql statements
        style = color.no_style()


        with connection.schema_editor() as editor:
            editor.create_model(model)


        class Admin(admin.ModelAdmin):
            list_display = ['first_name', 'last_name']

        admin.site.register(model, Admin)

        return model

    def CreateDynamicModel(request):
        fields = {
        'first_name': models.CharField(max_length=255),
        'last_name': models.CharField(max_length=255),
        'info': models.CharField(max_length=255)
        }
        model=create_model('Ddee',fields,app_label='testapp')

0 个答案:

没有答案