How to query several similar databases using Peewee?

戏子无情 提交于 2019-12-06 14:22:11

Next is maybe not exact an answer to your problem, but what I tried myself - succesfully - is using a playhouse.Proxy instance for every schema I want to use, and refer to a corresponding proxy in the innerclass Meta. I guess this will work without proxies too. However, seems you are looking for cross-schema queries, and already figured out what I came up with just now.

#!/usr/bin/python

import sqlite3
import peewee
from peewee import *
from playhouse.proxy import *

database_a_proxy = Proxy()
database_b_proxy = Proxy()

class BaseModelA(Model):
    class Meta:
            database = database_a_proxy

class BaseModelB(Model):
    class Meta:
            database = database_b_proxy

class RelationInSchemaA(BaseModelA):
    textfield = CharField()

class RelationInSchemaB(BaseModelB):
    textfield = CharField()

database_a = SqliteDatabase('schemaA', **{})
database_b = SqliteDatabase('schemaB', **{})

database_a_proxy.initialize(database_a)
database_b_proxy.initialize(database_b)

try:
   RelationInSchemaA.create_table()
   RelationInSchemaB.create_table()
except:
   pass

RelationInSchemaA.create(textfield='Hello')  
RelationInSchemaB.create(textfield='PeeWee')

Well, this is possible with handcrafting generated code from pwiz.py. I am sure there is a more elegant and lazy (i.e. not eager) way to do this, too, using some kind of factory, but I did not spend much time on Python nor PeeWee yet. If so, pwiz.py should have an extra flag for this purpose too, I guess.

I think this way is simpler:

import modelsA as A
import modelsB as B

ca = A.Customers.get(A.Customers.customernumber == 12)
cb = B.Customers.get(B.Customers.customernumber == 12)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!