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_DBNAMEto set the database to use, default is “test”RM_HOSTdefault to “127.0.0.1”RM_PORTdefault to 28015RM_USERdefault to “admin” (the RethinkDB default user)RM_PASSWORDdefault to empty string (the RethinkDB default)RM_TIMEOUTdefault to 10 (in seconds)RM_SOFT_DELETEwith isFalseby 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:
idis set by RethinkDBcreated_atwhen you save an object without id (create)updated_atwhen you save an object with a given id (update)deleted_atis set to deleteddatatimewhen you delete the object, and if you setrethinkmodel.db.SOFT_DELETEtoTrue
# 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]