Basic usage

First step

At first, you need to configure your database. Be sure that RethinkDB is launched and that you can access the service port.

By default, RethinkModel will check this environment variables:

  • RM_DBNAME to set the database to use, default is “test”

  • RM_HOST default to “127.0.0.1”

  • RM_PORT default to 28015

  • RM_USER default to “admin” (the RethinkDB default user)

  • RM_PASSWORD default to empty string (the RethinkDB default)

  • RM_TIMEOUT default to 10 (in seconds)

  • RM_SOFT_DELETE with is False by default

If you want to configure this in python, you can use the rethinkmodel.config() function.

Create models

The basic usage is to create a class with annotations to declare fields to save.

There are 4 automatic fields comming from Model class:

  • id is set by RethinkDB

  • created_at when you save an object without id (create)

  • updated_at when you save an object with a given id (update)

  • deleted_at is set to deleted datatime when you delete the object, and if you set rethinkmodel.db.SOFT_DELETE to True

# you must use typing
from typing import Type
from rethinkmodel import Model

class User(Model):
    username: str
    password: str
    age: int

Rethink:Model automatically manages One to One and One to Many relations. The rule is to add an annotations that is Typed with a Model based class. The above example can help:

class Post(Model):
    title: str
    author: User # this will actually store the User.id
    tags: str

class Product(Model):
    name: Optional[str] # we can accept None
    categories: List[str] # One to many

class Project(Model):
    name: str
    owner: Optional[User]

    # this will save a list of User IDs
    contributors: List[User]