如何用djang在postgresql中创建动态表

2024-04-26 12:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是上载一个.csv文件,并使用django将数据转储到postgresql数据库中。在

如何在postgresql中使用django动态创建一个表来将.csv数据转储到数据库中?在

我已经搜索并找到了一些例子,其中我们在创建表时必须给出属性名,但是在我的例子中,我不知道上传的.csv的属性名。在

我该怎么做?
如果有人能分享一些相关的链接,我将不胜感激。在


Tags: 文件csv数据django数据库属性链接postgresql
1条回答
网友
1楼 · 发布于 2024-04-26 12:57:52

你想要的是创建Dynamic Models。关于这一点,wiki上有一篇非常详细的文章:

  1. Django Dynamic Models它逐步解释了如何实现动态模型。这篇文章的一个快速示例:

    实现一个能够按需构建模型的功能:

    def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
        """
        Create specified model
        """
        class Meta:
            # Using type('Meta', ...) gives a dictproxy error during model creation
            pass
    
        if app_label:
            # app_label must be set using the Meta inner class
            setattr(Meta, 'app_label', app_label)
    
        # Update Meta with any options that were provided
        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__': module, 'Meta': Meta}
    
        # 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)
    
        # Create an Admin class if admin options were provided
        if admin_opts is not None:
            class Admin(admin.ModelAdmin):
                pass
            for key, value in admin_opts:
                setattr(Admin, key, value)
            admin.site.register(model, Admin)
    
        return model
    

    现在,您可以解析CSV文件并确定字段,然后创建模型:

    ^{pr2}$

    当然,你可以做更复杂的模型。阅读wiki以获得更彻底的解释。

  2. 存在这样一个django包:django-dynamic-model,它声称在django上添加动态模型创建(我无法确认是否有效):

    from dynamicmodel.models import DynamicModel, DynamicSchema, DynamicForm
    
     def csv_to_model(path_to_csv):
        with open(path_to_csv, "rb") as f:
            reader = csv.reader(f)
            col_names = next(reader)
    
        schema = DynamicSchema.get_for_model(MyModel)
        for name in col_names:
            schema.add_field(name=name, type='CharField')
    
        return schema
    

相关问题 更多 >