|
1 | 1 | ## Declaring models |
2 | 2 |
|
3 | 3 | You can define models by inheriting from `orm.Model` and |
4 | | -defining model fields as attributes in the class. |
| 4 | +defining model fields in the `fields` attribute. |
5 | 5 | For each defined model you need to set two special variables: |
6 | 6 |
|
7 | | -* `__database__` for database connection. |
8 | | -* `__metadata__` for `SQLAlchemy` functions and migrations. |
| 7 | +* `registry` an instance of `orm.ModelRegistry` |
| 8 | +* `fields` a `dict` of `orm` fields |
9 | 9 |
|
10 | | -You can also specify the table name in database by setting `__tablename__` attribute. |
| 10 | +You can also specify the table name in database by setting `tablename` attribute. |
11 | 11 |
|
12 | 12 | ```python |
13 | 13 | import databases |
14 | 14 | import orm |
15 | | -import sqlalchemy |
16 | 15 |
|
17 | 16 | database = databases.Database("sqlite:///db.sqlite") |
18 | | -metadata = sqlalchemy.MetaData() |
| 17 | +models = orm.ModelRegistry(database=database) |
19 | 18 |
|
20 | 19 |
|
21 | 20 | class Note(orm.Model): |
22 | | - __tablename__ = "notes" |
23 | | - __database__ = database |
24 | | - __metadata__ = metadata |
25 | | - |
26 | | - id = orm.Integer(primary_key=True) |
27 | | - text = orm.String(max_length=100) |
28 | | - completed = orm.Boolean(default=False) |
| 21 | + tablename = "notes" |
| 22 | + registry = models |
| 23 | + fields = { |
| 24 | + "id": orm.Integer(primary_key=True), |
| 25 | + "text": orm.String(max_length=100), |
| 26 | + "completed": orm.Boolean(default=False), |
| 27 | + } |
29 | 28 | ``` |
30 | 29 |
|
31 | 30 | ORM can create or drop database and tables from models using SQLAlchemy. |
32 | | -For using these functions or `Alembic` migrations, you still have to |
33 | | -install a synchronous DB driver: [psycopg2][psycopg2] for PostgreSQL and [pymysql][pymysql] for MySQL. |
34 | | - |
35 | | -Afer installing a synchronous DB driver, you can create tables for the models using: |
| 31 | +You can use the following methods: |
36 | 32 |
|
37 | 33 | ```python |
38 | | -engine = sqlalchemy.create_engine(str(database.url)) |
39 | | -metadata.create_all(engine) |
| 34 | +models.create_all() |
| 35 | + |
| 36 | +models.drop_all() |
40 | 37 | ``` |
41 | 38 |
|
42 | 39 | ## Data types |
@@ -72,6 +69,4 @@ See `TypeSystem` for [type-specific validation keyword arguments][typesystem-fie |
72 | 69 | * `orm.UUID()` |
73 | 70 | * `orm.JSON()` |
74 | 71 |
|
75 | | -[psycopg2]: https://www.psycopg.org/ |
76 | | -[pymysql]: https://github.com/PyMySQL/PyMySQL |
77 | 72 | [typesystem-fields]: https://www.encode.io/typesystem/fields/ |
0 commit comments