Skip to content
Andrei Horak edited this page Jun 8, 2019 · 2 revisions

Create a model

Creating models with remodel is extremely simple:

from remodel.models import Model

class User(Model):
    pass

Because remodel doesn't enforce any model schema, you don't need to declare any fields on your model; instead, just use them on any object!

Create tables

A model is the reflection of a data store table, so we need to create a table for the above created model. Luckily, remodel has a helper method which does just that!

from remodel.utils import create_tables

create_tables()

The above call to create_tables() creates a table named users in RethinkDB.

Configure database connection

Setups are widely different, so here's how you need to configure remodel in order to connect to your RethinkDB database:

from remodel.connection import pool

pool.configure(host='localhost', port=28015, auth_key=None, user='admin', password='', db='test')

Playing with our model

remodel features CRUD support for declared models. So, continuing with our example, you can create an object:

user = User(name='Andrei', github_username='linkyndy')

and then save it:

user.save()

You can then fetch a user from the data store:

user = User.get(name='Andrei')

and maybe delete it:

user.delete()

Creating relations

RethinkDB's major advantage over other NoSQLs is the built-in support for table joins, leveraging the creation of relations between models. remodel takes advantage of this great feature and allows you to create relations between models and use them to perform various operations on related data.

Here's how to create a basic relation:

from remodel.models import Model
from remodel.utils import create_tables, create_indexes

class Country(Model):
    has_many = ('City',)

class City(Model):
    belongs_to = ('Country',)

create_tables()
create_indexes()

A short summary on what we've done above:

  • we created two models, Country and City;
  • we stated that a Country may have multiple related City objects;
  • we created the tables for the two models, plus the indexes required for the relations to work

Playing with relations

Continuing with our models, we first create a country (note that create() also saves the new object):

romania = Country.create(name='Romania', continent='Europe')

Then, we want to create a couple of cities for Romania. Piece of cake:

timisoara = City.create(name='Timisoara', country=romania)
bucharest = City.create(name='Bucharest', country=romania)

So, we have one country with two cities in it. Don't believe me? You can verify this:

romania = Country.get(name='Romania')
print len(romania['cities']) # it yields 2!

Want to create one more romanian city? It's as simple as:

romania['cities'].create(name='Sibiu')