现有表格的Django动态模型"不存在"

时间:2018-01-31 19:34:21

标签: python django

我尝试从现有MySQL表中获取数据,并使用this solution中的代码将其放入模型中:

addEventListener

然后我按如下方式调用该类:

,  CASE WHEN datediff(day, a.Start_Date, a.End_Date) + 1 - DAY(a.END_Date) < DAY(a.END_DATE) THEN MONTH(a.End_Date) 
    ELSE MONTH(a.Start_Date) END AS Main_Month
 , CASE WHEN YEAR(a.END_Date) = YEAR(a.Start_Date) THEN YEAR(a.Start_Date)
        WHEN datediff(day, a.Start_Date, a.End_Date) + 1 - DAY(a.END_Date) < DAY(a.END_DATE) THEN  YEAR(a.End_Date) 
    ELSE YEAR(a.Start_Date) END AS Main_Year

并将其传递给DataPool(使用Django&#39的Chartit创建图表):

def getModel(table_name):
  class MyClassMetaclass(models.base.ModelBase):
    def __new__(cls, name, bases, attrs):
      name += table_name
      return models.base.ModelBase.__new__(cls, name, bases, attrs)

  class MyClass(models.Model):
    __metaclass__ = MyClassMetaclass
    time_stamp = models.DateTimeField(db_column='Time_stamp', blank=True, null=True)  # Field name made lowercase.
    price = models.DecimalField(db_column='Price', max_digits=8, decimal_places=3, blank=True,
                                null=True)  # Field name made lowercase.

    class Meta:
      db_table = table_name
      managed = False

  return MyClass

此时它会抛出错误(1146,&#34;表&#39; meowdb.test_table&#39;不存在&#34;)。请注意,meowdb是数据库名称。它应该在此之前吗?

我也没有在任何地方主动将数据库传递到模型中。根据{{​​3}},似乎一旦模型被创建,Django会根据名称自动链接它吗?

最后,我该如何解决这个错误?该表肯定存在,并且填充了许多行。

1 个答案:

答案 0 :(得分:0)

Okay, turns out I was being a moron. I used Django to auto-generate the models and then picked one at random to try using the flexible model code with. I just so happened to pick one with a space in it's table name. The class model name showed up without spaces of course and I didn't realise it. So the table genuinely wasn't there!

相关问题