1

I would like to have a possibility on merging two or more tables (generated by django-tables2) which are generated from dynamic models.

Let me first describe my problem:

I have the following fields for a dynamically generated model:

...
fields = {
    'colA': models.IntegerField(),
    'colB': models.IntegerField(),
    'colC': models.IntegerField(),
    'colD': models.IntegerField(),
}
...

The dynamic handling gives me the possibility to store my tables structered, without defining redundant model classes.

Example for models derived from stored tables in the database:

myDynamicModelA = DataModels().create_model('myDynamicModelA_tablename')
myDynamicModelB = DataModels().create_model('myDynamicModelB_tablename')
myDynamicModelC = DataModels().create_model('myDynamicModelC_tablename')
myDynamicModelD = DataModels().create_model('myDynamicModelD_tablename')
....

'_tablename' is commonly shared by all tables. What differs is the prefix 'myDynamicModel A,B,C...'

This is the model-part.

According to that let me describe the table structure by using django-tables2:

Each model/table shares some columns/fields, so that I can define a django-tables2 class like this:

class Table_A(tables.Table):
    colA = tables.Column()
    colB = tables.Column()

The fields which are different can be handled simply by using inheritance:

class Table_B(Table_A):
    colC = tables.Column()
    colD = tables.Column()

    def __init__(self, *args, **kwargs):
        self.colname = kwargs['colname']
        kwargs.pop('colname')
        super(Table_B, self).__init__(*args, **kwargs)
        for col in self.base_columns:
            if col not in ['colA', 'colB']:
                self.base_columns[col].verbose_name = '%s_%s' % (self.colname, col) 

As you can see, the constructor gives a different column-name-prefix for fields that differ across the models.

Now it is possible to generate tables from the different models, eg:

Table for 'myDynamicModelA_tablename':

columns: colA, colB, myDynamicModelA_tablename_colC, myDynamicModelA_tablename_colD

Table for 'myGenericModelB_tablename':

columns: colA, colB, myDynamicModelB_tablename_colC, myDynamicModelB_tablename_colD

...

Now my question: is it possible to merge both tables so that I receive something like that:

colA, colB, myDynamicModelA_tablename_colC, myDynamicModelB_tablename_colC, myDynamicModelA_tablename_colD, myDynamicModelB_tablename_colD

The values which will be shown should result from an intersection between the tables (this is possible, because of the common values from colA, which could be interpreted as a primary key)

It is nessecary that the result is a django-tables2 object, because I want to provide pagination as well as sorting options.

I hope my descriptions were understandable, sorry if not.

Many thanks for your time and help.

noplacetoh1de
  • 219
  • 3
  • 12

1 Answers1

2

perhaps this prev question and answer of mine will help?

I access data from combined dynamically created tables via raw sql and send this data to be rendered in a Django-Tables2

If you want to specify the order of and indeed which columns are rendered, define a Meta Class as shown below (where 'sequence' is the order of the columns; nb '...' just means 'and all other columns' - check out the documentary for Tables2 [search for 'Swapping the position of columns']):

def getTable(table_name):
    cursor = runSQL(table_name,"""
        SELECT * FROM subscription_exptinfo,%s
        WHERE %s.id = subscription_exptinfo.id
        ;""" %(table_name,table_name)) 

    exptData = dictfetchall(cursor)

    class Meta:
        attrs = {'class': 'paleblue'}
        sequence = ('id','...')              


    attrs = {}
    attrs['Meta'] = Meta
    cols=exptData[0]

    for item in cols:
        if item=='timeStart': 
            attrs[str(item)] = tables.DateTimeColumn(format='d-m-Y g:i:s',short=False)
        else:
            attrs[str(item)] = tables.Column()


    myTable = type('myTable', (TableReport,), attrs)   

    #TableOptions(table).sequence = ["Id","..."]
    #print ".........................." + str(TableOptions(table).sequence)


    return myTable(exptData)
Community
  • 1
  • 1
andyw
  • 3,505
  • 2
  • 30
  • 44