I have two tables with a 1-n relationship and I would like to insert data in these tables using bulk_create().
Let's take the User and Tweet example.
from peewee import *
db = SqliteDatabase('my_app.db')
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = CharField(unique=True)
class Tweet(BaseModel):
user = ForeignKeyField(User, backref='tweets')
message = TextField()
I would like to create unsaved instances of User and Tweet and to load them with bulk_create(). A naive solution would be:
db.create_tables([User, Tweet])
john = User(username='John')
mehdi = User(username='Mehdi')
users = [john, mehdi]
tweets = [Tweet(user=john, message='Hello twitter world!'),
Tweet(user=mehdi, message='This is my first message.'),
Tweet(user=mehdi, message='This is my second message.')]
User.bulk_create(users)
Tweet.bulk_create(tweets)
Unfortunately, this does not work because the User instances primary keys are not updated (as stated in the documentation except for Postgres databases).
As it seems impossible to update the primary key of the User instances (even if it were possible, it would probably be very inefficient to read the primary keys from the database), the only solution I can see is to use my own primary key and set it when creating the instance. This would mean not using the very convenient auto-incrementing primary key system of peewee and I would like too know if there is any alternative before to go that way.