Creating a new record

You can use Model.create() to create a new model instance. This method accepts keyword arguments, where the keys correspond to the names of the model’s fields. A new instance is returned and a row is added to the table.

  1. >>> User.create(username='Charlie')
  2. <__main__.User object at 0x2529350>

This will INSERT a new row into the database. The primary key will automatically be retrieved and stored on the model instance.

Alternatively, you can build up a model instance programmatically and then call save():

  1. >>> user = User(username='Charlie')
  2. >>> user.save() # save() returns the number of rows modified.
  3. 1
  4. >>> user.id
  5. 1
  6. >>> huey = User()
  7. >>> huey.username = 'Huey'
  8. >>> huey.save()
  9. 1
  10. >>> huey.id
  11. 2

When a model has a foreign key, you can directly assign a model instance to the foreign key field when creating a new record.

  1. >>> tweet = Tweet.create(user=huey, message='Hello!')

You can also use the value of the related object’s primary key:

  1. >>> tweet = Tweet.create(user=2, message='Hello again!')

If you simply wish to insert data and do not need to create a model instance, you can use Model.insert():

  1. >>> User.insert(username='Mickey').execute()
  2. 3

After executing the insert query, the primary key of the new row is returned.

Note

There are several ways you can speed up bulk insert operations. Check out the Bulk inserts recipe section for more information.