问题
I'm stuck with a problem about querying multiple databases using Peewee:
- I have 2 existing mysql databases (let's name them A and B) (Structures are similar because it's two Bugzilla databases)
- I generate models (modelsA.py and modelsB.py) using Pwiz
- I write this code:
.
from modelsA import *
from modelsB import *
The problem is: as the classes in modelsB are (sometimes) the same than modelsA, modelsB classes "overwrite" modelsA classes, making impossible to query A.
Besides, I don't understand how to query one of the specific database. For example, with this code:
c = Customers.get(Customers.customernumber == 12)
How do you know on which database this query is gonna be executed?
I had an idea, but it seems dirty to me: I could manually rename classes from modelsA.py and modelsB.py to make them distincts and then write this code:
ca = CustomersA.get(CustomersA.customernumber == 12)
cb = CustomersB.get(CustomersB.customernumber == 12)
Roughly, is Peewee able to deal with these kind of cases? If so, what is the way to do? Snippets would be very appreciated ^^ Thanks.
回答1:
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.
回答2:
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)
来源:https://stackoverflow.com/questions/20003916/how-to-query-several-similar-databases-using-peewee