0

i'm new in django/python. I have a function in the code that my boss gave to me that creates a new table everyday since 2012 using a static table as a model. So, my question is: How can i retrieve the data of the daily tables using the static table? Something like:

models.py

class report_2015_03_20(models.Model):
    name = models.CharField(max_length=50)
    class Meta:
        managed = False
        db_table = 'report_2015_03_20'

class report_2015_03_21(models.Model):
    name = models.CharField(max_length=50)
    class Meta:
        managed = False
        db_table = 'report_2015_03_20'

class report_2015_03_22(models.Model):
    name = models.CharField(max_length=50)
    class Meta:
        managed = False
        db_table = 'report_2015_03_20'

And i need to consult passing meta as a parameter:

class report(models.Model):
    name = models.CharField(max_length=50)

    class Meta:
        db_table = 'report_x_x_x'

Any help or ideia will me nice. Thanks

fasolo
  • 41
  • 1
  • 9

1 Answers1

0

I don't understand why this is necessary and don't think it's a great idea. However, it was a challenging question, so here is how you would do this (using type to dynamically create classes):

import datetime
from datetime import timedelta
from django.db import models
import __main__

# http://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)

class_list = []
for each_date in daterange(datetime.date(2012, 1, 1), datetime.date.today()):
    date_string = each_date.strftime('%Y_%m_%d')
    setattr(__main__,
        'report_' + date_string,
        type('report_' + date_string, (), {'name': models.CharField(max_length=50), 'Meta': type('Meta', (), {'managed': False, 'db_table': 'report_' + date_string})})
        )
jdotjdot
  • 16,134
  • 13
  • 66
  • 118