[Answered ]-How to create dynamic table in postgresql with django

2👍

What you want is to create Dynamic Models. There is a very detailed wiki article about that:

  1. Django Dynamic Models which explains step by step how to achieve a dynamic model. A quick sample from that article:

    Implement a function able to build a model on demand:

    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
    

    Now you can parse your CSV file and decide about your fields and then create your model:

    import csv
    
    def csv_to_model(path_to_csv):
        with open(path_to_csv, "rb") as f:
            reader = csv.reader(f)
            col_names = next(reader)
    
        fields = {}
        for name in col_names:
            fields[name] =  models.CharField()
    
        return create_model(fields)
    

    Of course, you can make more complicated models. Read the wiki for a more thorough explanation.

  2. There exist this django package: django-dynamic-model which claims to add dynamic model creation on django (I cannot confirm that works):

    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
    

Leave a comment