Reputation: 6755
I need to create two tables in peewee
. The tables are exactly the same, but one is temporary.
This is the definition of the table model:
class my_table(Model):
user_id = BigIntegerField(primary_key = True)
created_date = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
Now I need to also create a temporary table my_table_temp
which is an exact copy of my_table
.
Yet I noticed that if I do my_table_temp = my_table
when I do my_table_temp.create_table()
I actually create in my database a table named my_table
.
Is there a better way than redundantly
class my_table(Model):
user_id = BigIntegerField(primary_key = True)
created_date = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
class my_table_temp(Model):
user_id = BigIntegerField(primary_key = True)
created_date = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
Upvotes: 0
Views: 207
Reputation: 3626
Why not simply extend my_table
and do nothing else,
class my_table(Model):
user_id = BigIntegerField(primary_key=True)
created_date = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
class my_table_temp(my_table):
pass
Upvotes: 3
Reputation: 12773
Extending Wojciech's comment, why not use e.g.
my_table_temp = type("my_table_temp", (my_table,), {} )
Or if using CamelCase as recommended,
MyTableTemp = type("MyTableTemp", (MyTable,), {} )
For details on using type
to dynamically create classes, see here:
https://docs.python.org/3/library/functions.html#type
or using types
:
https://docs.python.org/3/library/types.html
Upvotes: 0
Reputation: 4294
What about this solution?
def create_table():
class TableClass(Model):
user_id = BigIntegerField(primary_key = True)
created_date = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
return TableClass
myTable = create_table()
myTempTable = create_table()
Upvotes: 2