Django 1.11-使用模型查询克隆表

时间:2018-11-21 16:23:11

标签: django

我有一张桌子

core_people

和一个备份表:

core_people_01

可以使用People Django模型在“克隆”表上进行查询吗?

类似这样的东西:

People.objects.get(pk = 123).table("people_01")

我在线搜索没有成功。

评论后更新 阅读有关SO的另一篇文章,我已经尝试过该解决方案。在我的模型文件中,我使用了以下方法:

def get_model(db_table):
  class MyClassMetaclass(People):
    def __new__(cls, name, bases, attrs):
      name += db_table
      return People.__new__(cls, name, bases, attrs)

  class MyClass(models.Model):
    __metaclass__ = MyClassMetaclass

    class Meta:
      db_table = db_table

  return MyClass

与它一起使用:

backup_people = get_model("core_people_01")
print (backup_people .objects.get(pk = 1234))

Pylint告诉我MyClassMetaclass无效,因为MetaClass并尝试执行上述指令,python告诉我:

RuntimeWarning: Model 'myclassmetaclass.core' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.

2 个答案:

答案 0 :(得分:0)

如果您是从同一模型中创建表,则可以访问模型的_meta属性,以指定要使用的表名。

  

People._meta.db_table ='core_people_01'

     

People.objects.all()   ```

答案 1 :(得分:0)

如果这是一个永久性要求,我将通过以下方式使用模型继承:

1)将People模型转换为抽象模型:

class AbstractPeople(models.Model):
    # Here your fields as in the original People model
    class Meta:
        abstract = True

2)创建两个从AbstractPeople延伸的具体模型

class People(AbstractPeople):
    pass

class BackupPeople(AbstractPeople):
    class Meta:
        db_table = 'core_people_01'
        # You can include this if your table already exists 
        # and do not want Django to mess around with it
        managed = False

通过这种方式,两个模型具有相同的结构,但是它们只是从不同的表中获取数据。