From 7d5e291a19e2ed21f264a17970e6ffd31ef1c73c Mon Sep 17 00:00:00 2001 From: collerek Date: Sat, 31 Oct 2020 18:11:48 +0100 Subject: [PATCH] switch to equals in most of the code, fix dependencies, clean tests, make all not relation fields work with type hints --- README.md | 12 +-- docs/index.md | 12 +-- docs/models.md | 2 +- docs/queries.md | 50 +++++------ docs_src/fastapi/docs001.py | 12 +-- docs_src/fields/docs001.py | 14 +-- docs_src/fields/docs002.py | 14 +-- docs_src/fields/docs003.py | 14 +-- docs_src/fields/docs004.py | 12 +-- docs_src/models/docs001.py | 6 +- docs_src/models/docs002.py | 6 +- docs_src/models/docs003.py | 6 +- docs_src/models/docs004.py | 6 +- docs_src/models/docs005.py | 6 +- docs_src/models/docs008.py | 8 +- docs_src/models/docs009.py | 6 +- docs_src/models/docs010.py | 10 +-- docs_src/queries/docs001.py | 14 +-- docs_src/relations/docs001.py | 14 +-- docs_src/relations/docs002.py | 20 +++-- mypy.ini | 3 + ormar/fields/many_to_many.py | 71 +++++++++++++-- ormar/fields/model_fields.py | 102 +++++++++++----------- ormar/models/metaclass.py | 65 +++++++------- ormar/models/model.py | 46 +++++----- ormar/models/newbasemodel.py | 4 +- ormar/queryset/queryset.py | 2 +- ormar/relations/querysetproxy.py | 10 +-- ormar/relations/relation.py | 14 +-- ormar/relations/relation_manager.py | 2 +- tests/test_aliases.py | 26 +++--- tests/test_columns.py | 17 ++-- tests/test_fastapi_docs.py | 12 +-- tests/test_fastapi_usage.py | 12 +-- tests/test_foreign_keys.py | 56 ++++++------ tests/test_many_to_many.py | 21 +++-- tests/test_model_definition.py | 83 +++++++++++------- tests/test_models.py | 30 +++---- tests/test_more_reallife_fastapi.py | 12 +-- tests/test_more_same_table_joins.py | 31 +++---- tests/test_new_annotation_style.py | 34 ++++---- tests/test_non_integer_pkey.py | 4 +- tests/test_queryset_level_methods.py | 26 +++--- tests/test_same_table_joins.py | 31 +++---- tests/test_selecting_subset_of_columns.py | 22 ++--- tests/test_server_default.py | 10 +-- tests/test_unique_constraints.py | 6 +- 47 files changed, 558 insertions(+), 438 deletions(-) diff --git a/README.md b/README.md index d6ff26c..2a5988b 100644 --- a/README.md +++ b/README.md @@ -75,8 +75,8 @@ class Album(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(length=100) class Track(ormar.Model): @@ -85,10 +85,10 @@ class Track(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - album: ormar.ForeignKey(Album) - title: ormar.String(length=100) - position: ormar.Integer() + id = ormar.Integer(primary_key=True) + album= ormar.ForeignKey(Album) + title = ormar.String(length=100) + position = ormar.Integer() # Create some records to work with. diff --git a/docs/index.md b/docs/index.md index ca77b54..3d0f507 100644 --- a/docs/index.md +++ b/docs/index.md @@ -75,8 +75,8 @@ class Album(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(length=100) class Track(ormar.Model): @@ -85,10 +85,10 @@ class Track(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - album: ormar.ForeignKey(Album) - title: ormar.String(length=100) - position: ormar.Integer() + id = ormar.Integer(primary_key=True) + album: Optional[Album] =ormar.ForeignKey(Album) + title = ormar.String(length=100) + position = ormar.Integer() # Create some records to work with. diff --git a/docs/models.md b/docs/models.md index 3562a7b..cb063fb 100644 --- a/docs/models.md +++ b/docs/models.md @@ -34,7 +34,7 @@ By default if you assign primary key to `Integer` field, the `autoincrement` opt You can disable by passing `autoincremant=False`. ```Python -id: ormar.Integer(primary_key=True, autoincrement=False) +id = ormar.Integer(primary_key=True, autoincrement=False) ``` ### Fields names vs Column names diff --git a/docs/queries.md b/docs/queries.md index c3f0268..dd6e249 100644 --- a/docs/queries.md +++ b/docs/queries.md @@ -109,10 +109,10 @@ class Book(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - title: ormar.String(max_length=200) - author: ormar.String(max_length=100) - genre: ormar.String(max_length=100, default='Fiction', choices=['Fiction', 'Adventure', 'Historic', 'Fantasy']) + id = ormar.Integer(primary_key=True) + title = ormar.String(max_length=200) + author = ormar.String(max_length=100) + genre = ormar.String(max_length=100, default='Fiction', choices=['Fiction', 'Adventure', 'Historic', 'Fantasy']) await Book.objects.create(title='Tom Sawyer', author="Twain, Mark", genre='Adventure') await Book.objects.create(title='War and Peace', author="Tolstoy, Leo", genre='Fiction') @@ -146,10 +146,10 @@ class Book(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - title: ormar.String(max_length=200) - author: ormar.String(max_length=100) - genre: ormar.String(max_length=100, default='Fiction', choices=['Fiction', 'Adventure', 'Historic', 'Fantasy']) + id = ormar.Integer(primary_key=True) + title = ormar.String(max_length=200) + author = ormar.String(max_length=100) + genre = ormar.String(max_length=100, default='Fiction', choices=['Fiction', 'Adventure', 'Historic', 'Fantasy']) await Book.objects.create(title='Tom Sawyer', author="Twain, Mark", genre='Adventure') await Book.objects.create(title='War and Peace', author="Tolstoy, Leo", genre='Fiction') @@ -192,9 +192,9 @@ class ToDo(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - text: ormar.String(max_length=500) - completed: ormar.Boolean(default=False) + id = ormar.Integer(primary_key=True) + text = ormar.String(max_length=500) + completed= ormar.Boolean(default=False) # create multiple instances at once with bulk_create await ToDo.objects.bulk_create( @@ -259,10 +259,10 @@ class Book(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - title: ormar.String(max_length=200) - author: ormar.String(max_length=100) - genre: ormar.String(max_length=100, default='Fiction', choices=['Fiction', 'Adventure', 'Historic', 'Fantasy']) + id = ormar.Integer(primary_key=True) + title = ormar.String(max_length=200) + author = ormar.String(max_length=100) + genre = ormar.String(max_length=100, default='Fiction', choices=['Fiction', 'Adventure', 'Historic', 'Fantasy']) await Book.objects.create(title='Tom Sawyer', author="Twain, Mark", genre='Adventure') await Book.objects.create(title='War and Peace in Space', author="Tolstoy, Leo", genre='Fantasy') @@ -470,9 +470,9 @@ class Company(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - founded: ormar.Integer(nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + founded = ormar.Integer(nullable=True) class Car(ormar.Model): @@ -481,13 +481,13 @@ class Car(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - manufacturer: ormar.ForeignKey(Company) - name: ormar.String(max_length=100) - year: ormar.Integer(nullable=True) - gearbox_type: ormar.String(max_length=20, nullable=True) - gears: ormar.Integer(nullable=True) - aircon_type: ormar.String(max_length=20, nullable=True) + id = ormar.Integer(primary_key=True) + manufacturer= ormar.ForeignKey(Company) + name = ormar.String(max_length=100) + year = ormar.Integer(nullable=True) + gearbox_type = ormar.String(max_length=20, nullable=True) + gears = ormar.Integer(nullable=True) + aircon_type = ormar.String(max_length=20, nullable=True) diff --git a/docs_src/fastapi/docs001.py b/docs_src/fastapi/docs001.py index 475756a..7987bef 100644 --- a/docs_src/fastapi/docs001.py +++ b/docs_src/fastapi/docs001.py @@ -1,4 +1,4 @@ -from typing import List +from typing import List, Optional import databases import sqlalchemy @@ -32,8 +32,8 @@ class Category(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Item(ormar.Model): @@ -42,9 +42,9 @@ class Item(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - category: ormar.ForeignKey(Category, nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + category= ormar.ForeignKey(Category, nullable=True) @app.get("/items/", response_model=List[Item]) diff --git a/docs_src/fields/docs001.py b/docs_src/fields/docs001.py index 7cb26f4..304b92d 100644 --- a/docs_src/fields/docs001.py +++ b/docs_src/fields/docs001.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import sqlalchemy @@ -12,8 +14,8 @@ class Department(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Course(ormar.Model): @@ -21,10 +23,10 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) - department: ormar.ForeignKey(Department) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) + department= ormar.ForeignKey(Department) department = Department(name='Science') diff --git a/docs_src/fields/docs002.py b/docs_src/fields/docs002.py index 4a0c61f..13e4544 100644 --- a/docs_src/fields/docs002.py +++ b/docs_src/fields/docs002.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import sqlalchemy @@ -12,8 +14,8 @@ class Department(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Course(ormar.Model): @@ -21,10 +23,10 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) - department: ormar.ForeignKey(Department, related_name="my_courses") + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) + department= ormar.ForeignKey(Department, related_name="my_courses") department = Department(name='Science') diff --git a/docs_src/fields/docs003.py b/docs_src/fields/docs003.py index a0cb2c4..7a7f8b9 100644 --- a/docs_src/fields/docs003.py +++ b/docs_src/fields/docs003.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import sqlalchemy @@ -12,8 +14,8 @@ class Department(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Course(ormar.Model): @@ -21,7 +23,7 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) - department: ormar.ForeignKey(Department) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) + department= ormar.ForeignKey(Department) diff --git a/docs_src/fields/docs004.py b/docs_src/fields/docs004.py index b04cdb2..793dc93 100644 --- a/docs_src/fields/docs004.py +++ b/docs_src/fields/docs004.py @@ -1,3 +1,5 @@ +from datetime import datetime + import databases import sqlalchemy from sqlalchemy import func, text @@ -14,8 +16,8 @@ class Product(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - company: ormar.String(max_length=200, server_default='Acme') - sort_order: ormar.Integer(server_default=text("10")) - created: ormar.DateTime(server_default=func.now()) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + company = ormar.String(max_length=200, server_default='Acme') + sort_order = ormar.Integer(server_default=text("10")) + created= ormar.DateTime(server_default=func.now()) diff --git a/docs_src/models/docs001.py b/docs_src/models/docs001.py index 47b3581..78e2238 100644 --- a/docs_src/models/docs001.py +++ b/docs_src/models/docs001.py @@ -12,6 +12,6 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) diff --git a/docs_src/models/docs002.py b/docs_src/models/docs002.py index 96ee368..b8f206e 100644 --- a/docs_src/models/docs002.py +++ b/docs_src/models/docs002.py @@ -15,6 +15,6 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) diff --git a/docs_src/models/docs003.py b/docs_src/models/docs003.py index 91a83cf..92a7d49 100644 --- a/docs_src/models/docs003.py +++ b/docs_src/models/docs003.py @@ -12,9 +12,9 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) print(Course.__fields__) diff --git a/docs_src/models/docs004.py b/docs_src/models/docs004.py index a1db655..f40c1f1 100644 --- a/docs_src/models/docs004.py +++ b/docs_src/models/docs004.py @@ -12,9 +12,9 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) print(Course.Meta.table.columns) diff --git a/docs_src/models/docs005.py b/docs_src/models/docs005.py index ce81887..50e3515 100644 --- a/docs_src/models/docs005.py +++ b/docs_src/models/docs005.py @@ -12,9 +12,9 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) print({x:v.__dict__ for x,v in Course.Meta.model_fields.items()}) """ diff --git a/docs_src/models/docs008.py b/docs_src/models/docs008.py index 9a3d063..b7ab424 100644 --- a/docs_src/models/docs008.py +++ b/docs_src/models/docs008.py @@ -13,7 +13,7 @@ class Child(ormar.Model): metadata = metadata database = database - id: ormar.Integer(name='child_id', primary_key=True) - first_name: ormar.String(name='fname', max_length=100) - last_name: ormar.String(name='lname', max_length=100) - born_year: ormar.Integer(name='year_born', nullable=True) + id = ormar.Integer(name='child_id', primary_key=True) + first_name = ormar.String(name='fname', max_length=100) + last_name = ormar.String(name='lname', max_length=100) + born_year = ormar.Integer(name='year_born', nullable=True) diff --git a/docs_src/models/docs009.py b/docs_src/models/docs009.py index 0204feb..71b1bb3 100644 --- a/docs_src/models/docs009.py +++ b/docs_src/models/docs009.py @@ -4,6 +4,6 @@ class Album(ormar.Model): metadata = metadata database = database - id: ormar.Integer(name='album_id', primary_key=True) - name: ormar.String(name='album_name', max_length=100) - artist: ormar.ForeignKey(Artist, name='artist_id') + id = ormar.Integer(name='album_id', primary_key=True) + name = ormar.String(name='album_name', max_length=100) + artist= ormar.ForeignKey(Artist, name='artist_id') diff --git a/docs_src/models/docs010.py b/docs_src/models/docs010.py index 57febef..dd52267 100644 --- a/docs_src/models/docs010.py +++ b/docs_src/models/docs010.py @@ -11,8 +11,8 @@ class Artist(ormar.Model): metadata = metadata database = database - id: ormar.Integer(name='artist_id', primary_key=True) - first_name: ormar.String(name='fname', max_length=100) - last_name: ormar.String(name='lname', max_length=100) - born_year: ormar.Integer(name='year') - children: ormar.ManyToMany(Child, through=ArtistChildren) + id = ormar.Integer(name='artist_id', primary_key=True) + first_name = ormar.String(name='fname', max_length=100) + last_name = ormar.String(name='lname', max_length=100) + born_year = ormar.Integer(name='year') + children: Optional[Union[Child, List[Child]]] = ormar.ManyToMany(Child, through=ArtistChildren) diff --git a/docs_src/queries/docs001.py b/docs_src/queries/docs001.py index 2e4fe43..6edaa53 100644 --- a/docs_src/queries/docs001.py +++ b/docs_src/queries/docs001.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import ormar import sqlalchemy @@ -12,8 +14,8 @@ class Album(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Track(ormar.Model): @@ -22,7 +24,7 @@ class Track(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - album: ormar.ForeignKey(Album) - title: ormar.String(max_length=100) - position: ormar.Integer() \ No newline at end of file + id = ormar.Integer(primary_key=True) + album= ormar.ForeignKey(Album) + title = ormar.String(max_length=100) + position = ormar.Integer() \ No newline at end of file diff --git a/docs_src/relations/docs001.py b/docs_src/relations/docs001.py index 930e8d3..6425f39 100644 --- a/docs_src/relations/docs001.py +++ b/docs_src/relations/docs001.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import sqlalchemy @@ -12,8 +14,8 @@ class Department(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Course(ormar.Model): @@ -21,10 +23,10 @@ class Course(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - completed: ormar.Boolean(default=False) - department: ormar.ForeignKey(Department) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + completed= ormar.Boolean(default=False) + department= ormar.ForeignKey(Department) department = Department(name='Science') diff --git a/docs_src/relations/docs002.py b/docs_src/relations/docs002.py index f78083a..470d9b1 100644 --- a/docs_src/relations/docs002.py +++ b/docs_src/relations/docs002.py @@ -1,3 +1,5 @@ +from typing import Optional, Union, List + import databases import ormar import sqlalchemy @@ -12,9 +14,9 @@ class Author(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - first_name: ormar.String(max_length=80) - last_name: ormar.String(max_length=80) + id = ormar.Integer(primary_key=True) + first_name = ormar.String(max_length=80) + last_name = ormar.String(max_length=80) class Category(ormar.Model): @@ -23,8 +25,8 @@ class Category(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=40) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=40) class PostCategory(ormar.Model): @@ -42,7 +44,7 @@ class Post(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - title: ormar.String(max_length=200) - categories: ormar.ManyToMany(Category, through=PostCategory) - author: ormar.ForeignKey(Author) + id = ormar.Integer(primary_key=True) + title = ormar.String(max_length=200) + categories: Optional[Union[Category, List[Category]]] = ormar.ManyToMany(Category, through=PostCategory) + author= ormar.ForeignKey(Author) diff --git a/mypy.ini b/mypy.ini index 6347ae1..108c485 100644 --- a/mypy.ini +++ b/mypy.ini @@ -5,3 +5,6 @@ plugins = pydantic.mypy [mypy-sqlalchemy.*] ignore_missing_imports = True +[mypy-tests.test_model_definition.*] +ignore_errors = True + diff --git a/ormar/fields/many_to_many.py b/ormar/fields/many_to_many.py index 5c81182..5160a26 100644 --- a/ormar/fields/many_to_many.py +++ b/ormar/fields/many_to_many.py @@ -1,4 +1,4 @@ -from typing import Any, List, Optional, TYPE_CHECKING, Type, Union +from typing import Any, List, Optional, TYPE_CHECKING, Type, Union, Sequence from ormar.fields import BaseField from ormar.fields.foreign_key import ForeignKeyField @@ -10,13 +10,13 @@ REF_PREFIX = "#/components/schemas/" def ManyToMany( - to: Type["Model"], - through: Type["Model"], - *, - name: str = None, - unique: bool = False, - virtual: bool = False, - **kwargs: Any + to: Type["Model"], + through: Type["Model"], + *, + name: str = None, + unique: bool = False, + virtual: bool = False, + **kwargs: Any ) -> Type["ManyToManyField"]: to_field = to.Meta.model_fields[to.Meta.pkname] related_name = kwargs.pop("related_name", None) @@ -49,3 +49,58 @@ def ManyToMany( class ManyToManyField(ForeignKeyField): through: Type["Model"] + + if TYPE_CHECKING: # pragma nocover + @staticmethod + async def add(item: "Model") -> None: + pass + + @staticmethod + async def remove(item: "Model") -> None: + pass + + from ormar import QuerySet + + @staticmethod + def filter(**kwargs: Any) -> "QuerySet": # noqa: A003 + pass + + @staticmethod + def select_related(related: Union[List, str]) -> "QuerySet": + pass + + @staticmethod + async def exists(self) -> bool: + return await self.queryset.exists() + + @staticmethod + async def count(self) -> int: + return await self.queryset.count() + + @staticmethod + async def clear(self) -> int: + pass + + @staticmethod + def limit(limit_count: int) -> "QuerySet": + pass + + @staticmethod + def offset(self, offset: int) -> "QuerySet": + pass + + @staticmethod + async def first(self, **kwargs: Any) -> "Model": + pass + + @staticmethod + async def get(self, **kwargs: Any) -> "Model": + pass + + @staticmethod + async def all(self, **kwargs: Any) -> Sequence[Optional["Model"]]: # noqa: A003 + pass + + @staticmethod + async def create(self, **kwargs: Any) -> "Model": + pass diff --git a/ormar/fields/model_fields.py b/ormar/fields/model_fields.py index 2e98018..9c53574 100644 --- a/ormar/fields/model_fields.py +++ b/ormar/fields/model_fields.py @@ -12,7 +12,7 @@ from ormar.fields.base import BaseField # noqa I101 def is_field_nullable( - nullable: Optional[bool], default: Any, server_default: Any + nullable: Optional[bool], default: Any, server_default: Any ) -> bool: if nullable is None: return default is not None or server_default is not None @@ -58,20 +58,20 @@ class ModelFieldFactory: pass -class String(ModelFieldFactory): +class String(ModelFieldFactory, str): _type = str _pydantic_type = pydantic.ConstrainedStr def __new__( # type: ignore # noqa CFQ002 - cls, - *, - allow_blank: bool = True, - strip_whitespace: bool = False, - min_length: int = None, - max_length: int = None, - curtail_length: int = None, - regex: str = None, - **kwargs: Any + cls, + *, + allow_blank: bool = True, + strip_whitespace: bool = False, + min_length: int = None, + max_length: int = None, + curtail_length: int = None, + regex: str = None, + **kwargs: Any ) -> Type[BaseField]: # type: ignore kwargs = { **kwargs, @@ -97,17 +97,17 @@ class String(ModelFieldFactory): ) -class Integer(ModelFieldFactory): +class Integer(ModelFieldFactory, int): _type = int _pydantic_type = pydantic.ConstrainedInt def __new__( # type: ignore - cls, - *, - minimum: int = None, - maximum: int = None, - multiple_of: int = None, - **kwargs: Any + cls, + *, + minimum: int = None, + maximum: int = None, + multiple_of: int = None, + **kwargs: Any ) -> Type[BaseField]: autoincrement = kwargs.pop("autoincrement", None) autoincrement = ( @@ -132,12 +132,12 @@ class Integer(ModelFieldFactory): return sqlalchemy.Integer() -class Text(ModelFieldFactory): +class Text(ModelFieldFactory, str): _type = str _pydantic_type = pydantic.ConstrainedStr def __new__( # type: ignore - cls, *, allow_blank: bool = True, strip_whitespace: bool = False, **kwargs: Any + cls, *, allow_blank: bool = True, strip_whitespace: bool = False, **kwargs: Any ) -> Type[BaseField]: kwargs = { **kwargs, @@ -155,17 +155,17 @@ class Text(ModelFieldFactory): return sqlalchemy.Text() -class Float(ModelFieldFactory): +class Float(ModelFieldFactory, float): _type = float _pydantic_type = pydantic.ConstrainedFloat def __new__( # type: ignore - cls, - *, - minimum: float = None, - maximum: float = None, - multiple_of: int = None, - **kwargs: Any + cls, + *, + minimum: float = None, + maximum: float = None, + multiple_of: int = None, + **kwargs: Any ) -> Type[BaseField]: kwargs = { **kwargs, @@ -184,7 +184,7 @@ class Float(ModelFieldFactory): return sqlalchemy.Float() -class Boolean(ModelFieldFactory): +class Boolean(ModelFieldFactory, int): _type = bool _pydantic_type = bool @@ -193,7 +193,7 @@ class Boolean(ModelFieldFactory): return sqlalchemy.Boolean() -class DateTime(ModelFieldFactory): +class DateTime(ModelFieldFactory, datetime.datetime): _type = datetime.datetime _pydantic_type = datetime.datetime @@ -202,7 +202,7 @@ class DateTime(ModelFieldFactory): return sqlalchemy.DateTime() -class Date(ModelFieldFactory): +class Date(ModelFieldFactory, datetime.date): _type = datetime.date _pydantic_type = datetime.date @@ -211,7 +211,7 @@ class Date(ModelFieldFactory): return sqlalchemy.Date() -class Time(ModelFieldFactory): +class Time(ModelFieldFactory, datetime.time): _type = datetime.time _pydantic_type = datetime.time @@ -220,7 +220,7 @@ class Time(ModelFieldFactory): return sqlalchemy.Time() -class JSON(ModelFieldFactory): +class JSON(ModelFieldFactory, pydantic.Json): _type = pydantic.Json _pydantic_type = pydantic.Json @@ -229,17 +229,17 @@ class JSON(ModelFieldFactory): return sqlalchemy.JSON() -class BigInteger(Integer): +class BigInteger(Integer, int): _type = int _pydantic_type = pydantic.ConstrainedInt def __new__( # type: ignore - cls, - *, - minimum: int = None, - maximum: int = None, - multiple_of: int = None, - **kwargs: Any + cls, + *, + minimum: int = None, + maximum: int = None, + multiple_of: int = None, + **kwargs: Any ) -> Type[BaseField]: autoincrement = kwargs.pop("autoincrement", None) autoincrement = ( @@ -264,21 +264,21 @@ class BigInteger(Integer): return sqlalchemy.BigInteger() -class Decimal(ModelFieldFactory): +class Decimal(ModelFieldFactory, decimal.Decimal): _type = decimal.Decimal _pydantic_type = pydantic.ConstrainedDecimal def __new__( # type: ignore # noqa CFQ002 - cls, - *, - minimum: float = None, - maximum: float = None, - multiple_of: int = None, - precision: int = None, - scale: int = None, - max_digits: int = None, - decimal_places: int = None, - **kwargs: Any + cls, + *, + minimum: float = None, + maximum: float = None, + multiple_of: int = None, + precision: int = None, + scale: int = None, + max_digits: int = None, + decimal_places: int = None, + **kwargs: Any ) -> Type[BaseField]: kwargs = { **kwargs, @@ -319,7 +319,7 @@ class Decimal(ModelFieldFactory): ) -class UUID(ModelFieldFactory): +class UUID(ModelFieldFactory, uuid.UUID): _type = uuid.UUID _pydantic_type = uuid.UUID diff --git a/ormar/models/metaclass.py b/ormar/models/metaclass.py index 798424b..8d264a5 100644 --- a/ormar/models/metaclass.py +++ b/ormar/models/metaclass.py @@ -42,7 +42,7 @@ def register_relation_on_build(table_name: str, field: Type[ForeignKeyField]) -> def register_many_to_many_relation_on_build( - table_name: str, field: Type[ManyToManyField] + table_name: str, field: Type[ManyToManyField] ) -> None: alias_manager.add_relation_type(field.through.Meta.tablename, table_name) alias_manager.add_relation_type( @@ -51,11 +51,11 @@ def register_many_to_many_relation_on_build( def reverse_field_not_already_registered( - child: Type["Model"], child_model_name: str, parent_model: Type["Model"] + child: Type["Model"], child_model_name: str, parent_model: Type["Model"] ) -> bool: return ( - child_model_name not in parent_model.__fields__ - and child.get_name() not in parent_model.__fields__ + child_model_name not in parent_model.__fields__ + and child.get_name() not in parent_model.__fields__ ) @@ -66,7 +66,7 @@ def expand_reverse_relationships(model: Type["Model"]) -> None: parent_model = model_field.to child = model if reverse_field_not_already_registered( - child, child_model_name, parent_model + child, child_model_name, parent_model ): register_reverse_model_fields( parent_model, child, child_model_name, model_field @@ -74,10 +74,10 @@ def expand_reverse_relationships(model: Type["Model"]) -> None: def register_reverse_model_fields( - model: Type["Model"], - child: Type["Model"], - child_model_name: str, - model_field: Type["ForeignKeyField"], + model: Type["Model"], + child: Type["Model"], + child_model_name: str, + model_field: Type["ForeignKeyField"], ) -> None: if issubclass(model_field, ManyToManyField): model.Meta.model_fields[child_model_name] = ManyToMany( @@ -92,7 +92,7 @@ def register_reverse_model_fields( def adjust_through_many_to_many_model( - model: Type["Model"], child: Type["Model"], model_field: Type[ManyToManyField] + model: Type["Model"], child: Type["Model"], model_field: Type[ManyToManyField] ) -> None: model_field.through.Meta.model_fields[model.get_name()] = ForeignKey( model, name=model.get_name(), ondelete="CASCADE" @@ -109,7 +109,7 @@ def adjust_through_many_to_many_model( def create_pydantic_field( - field_name: str, model: Type["Model"], model_field: Type[ManyToManyField] + field_name: str, model: Type["Model"], model_field: Type[ManyToManyField] ) -> None: model_field.through.__fields__[field_name] = ModelField( name=field_name, @@ -121,7 +121,7 @@ def create_pydantic_field( def create_and_append_m2m_fk( - model: Type["Model"], model_field: Type[ManyToManyField] + model: Type["Model"], model_field: Type[ManyToManyField] ) -> None: column = sqlalchemy.Column( model.get_name(), @@ -137,7 +137,7 @@ def create_and_append_m2m_fk( def check_pk_column_validity( - field_name: str, field: BaseField, pkname: Optional[str] + field_name: str, field: BaseField, pkname: Optional[str] ) -> Optional[str]: if pkname is not None: raise ModelDefinitionError("Only one primary key column is allowed.") @@ -147,7 +147,7 @@ def check_pk_column_validity( def sqlalchemy_columns_from_model_fields( - model_fields: Dict, table_name: str + model_fields: Dict, table_name: str ) -> Tuple[Optional[str], List[sqlalchemy.Column]]: columns = [] pkname = None @@ -161,9 +161,9 @@ def sqlalchemy_columns_from_model_fields( if field.primary_key: pkname = check_pk_column_validity(field_name, field, pkname) if ( - not field.pydantic_only - and not field.virtual - and not issubclass(field, ManyToManyField) + not field.pydantic_only + and not field.virtual + and not issubclass(field, ManyToManyField) ): columns.append(field.get_column(field_name)) register_relation_in_alias_manager(table_name, field) @@ -171,7 +171,7 @@ def sqlalchemy_columns_from_model_fields( def register_relation_in_alias_manager( - table_name: str, field: Type[ForeignKeyField] + table_name: str, field: Type[ForeignKeyField] ) -> None: if issubclass(field, ManyToManyField): register_many_to_many_relation_on_build(table_name, field) @@ -180,7 +180,7 @@ def register_relation_in_alias_manager( def populate_default_pydantic_field_value( - ormar_field: Type[BaseField], field_name: str, attrs: dict + ormar_field: Type[BaseField], field_name: str, attrs: dict ) -> dict: curr_def_value = attrs.get(field_name, ormar.Undefined) if lenient_issubclass(curr_def_value, ormar.fields.BaseField): @@ -193,7 +193,7 @@ def populate_default_pydantic_field_value( def check_if_field_annotation_or_value_is_ormar( - field: Any, field_name: str, attrs: Dict + field: Any, field_name: str, attrs: Dict ) -> bool: return lenient_issubclass(field, BaseField) or issubclass( attrs.get(field_name, type), BaseField @@ -201,14 +201,16 @@ def check_if_field_annotation_or_value_is_ormar( def extract_field_from_annotation_or_value( - field: Any, field_name: str, attrs: Dict + field: Any, field_name: str, attrs: Dict ) -> Type[ormar.fields.BaseField]: return field if lenient_issubclass(field, BaseField) else attrs.get(field_name) def populate_pydantic_default_values(attrs: Dict) -> Tuple[Dict, Dict]: model_fields = {} - for field_name, field in attrs["__annotations__"].items(): + potential_fields = {k: v for k, v in attrs["__annotations__"].items() if lenient_issubclass(v, BaseField)} + potential_fields.update({k: v for k, v in attrs.items() if lenient_issubclass(v, BaseField)}) + for field_name, field in potential_fields.items(): # ormar fields can be used as annotation or as default value if check_if_field_annotation_or_value_is_ormar(field, field_name, attrs): ormar_field = extract_field_from_annotation_or_value( @@ -225,17 +227,16 @@ def populate_pydantic_default_values(attrs: Dict) -> Tuple[Dict, Dict]: def extract_annotations_and_default_vals( - attrs: dict, bases: Tuple + attrs: dict ) -> Tuple[Dict, Dict]: - attrs["__annotations__"] = attrs.get("__annotations__") or bases[0].__dict__.get( - "__annotations__", {} - ) + key = '__annotations__' + attrs[key] = attrs.get(key, {}) attrs, model_fields = populate_pydantic_default_values(attrs) return attrs, model_fields def populate_meta_tablename_columns_and_pk( - name: str, new_model: Type["Model"] + name: str, new_model: Type["Model"] ) -> Type["Model"]: tablename = name.lower() + "s" new_model.Meta.tablename = ( @@ -261,7 +262,7 @@ def populate_meta_tablename_columns_and_pk( def populate_meta_sqlalchemy_table_if_required( - new_model: Type["Model"], + new_model: Type["Model"], ) -> Type["Model"]: if not hasattr(new_model.Meta, "table"): new_model.Meta.table = sqlalchemy.Table( @@ -276,7 +277,7 @@ def populate_meta_sqlalchemy_table_if_required( def get_pydantic_base_orm_config() -> Type[BaseConfig]: class Config(BaseConfig): orm_mode = True - arbitrary_types_allowed = True + # arbitrary_types_allowed = True return Config @@ -303,7 +304,7 @@ def choices_validator(cls: Type["Model"], values: Dict[str, Any]) -> Dict[str, A def populate_choices_validators( # noqa CCR001 - model: Type["Model"], attrs: Dict + model: Type["Model"], attrs: Dict ) -> None: if model_initialized_and_has_model_fields(model): for _, field in model.Meta.model_fields.items(): @@ -316,11 +317,11 @@ def populate_choices_validators( # noqa CCR001 class ModelMetaclass(pydantic.main.ModelMetaclass): def __new__( # type: ignore - mcs: "ModelMetaclass", name: str, bases: Any, attrs: dict + mcs: "ModelMetaclass", name: str, bases: Any, attrs: dict ) -> "ModelMetaclass": attrs["Config"] = get_pydantic_base_orm_config() attrs["__name__"] = name - attrs, model_fields = extract_annotations_and_default_vals(attrs, bases) + attrs, model_fields = extract_annotations_and_default_vals(attrs) new_model = super().__new__( # type: ignore mcs, name, bases, attrs ) diff --git a/ormar/models/model.py b/ormar/models/model.py index f8884b1..f8b6ea0 100644 --- a/ormar/models/model.py +++ b/ormar/models/model.py @@ -24,6 +24,9 @@ def group_related_list(list_: List) -> Dict: return test_dict +if TYPE_CHECKING: # pragma nocover + from ormar import QuerySet + T = TypeVar("T", bound="Model") @@ -31,6 +34,7 @@ class Model(NewBaseModel): __abstract__ = False if TYPE_CHECKING: # pragma nocover Meta: ModelMeta + objects: "QuerySet" def __repr__(self) -> str: # pragma nocover attrs_to_include = ["tablename", "columns", "pkname"] @@ -41,12 +45,12 @@ class Model(NewBaseModel): @classmethod def from_row( # noqa CCR001 - cls: Type[T], - row: sqlalchemy.engine.ResultProxy, - select_related: List = None, - related_models: Any = None, - previous_table: str = None, - fields: List = None, + cls: Type[T], + row: sqlalchemy.engine.ResultProxy, + select_related: List = None, + related_models: Any = None, + previous_table: str = None, + fields: List = None, ) -> Optional[T]: item: Dict[str, Any] = {} @@ -56,9 +60,9 @@ class Model(NewBaseModel): related_models = group_related_list(select_related) if ( - previous_table - and previous_table in cls.Meta.model_fields - and issubclass(cls.Meta.model_fields[previous_table], ManyToManyField) + previous_table + and previous_table in cls.Meta.model_fields + and issubclass(cls.Meta.model_fields[previous_table], ManyToManyField) ): previous_table = cls.Meta.model_fields[ previous_table @@ -86,12 +90,12 @@ class Model(NewBaseModel): @classmethod def populate_nested_models_from_row( - cls, - item: dict, - row: sqlalchemy.engine.ResultProxy, - related_models: Any, - previous_table: sqlalchemy.Table, - fields: List = None, + cls, + item: dict, + row: sqlalchemy.engine.ResultProxy, + related_models: Any, + previous_table: sqlalchemy.Table, + fields: List = None, ) -> dict: for related in related_models: if isinstance(related_models, dict) and related_models[related]: @@ -115,12 +119,12 @@ class Model(NewBaseModel): @classmethod def extract_prefixed_table_columns( # noqa CCR001 - cls, - item: dict, - row: sqlalchemy.engine.result.ResultProxy, - table_prefix: str, - fields: List = None, - nested: bool = False, + cls, + item: dict, + row: sqlalchemy.engine.result.ResultProxy, + table_prefix: str, + fields: List = None, + nested: bool = False, ) -> dict: # databases does not keep aliases in Record for postgres, change to raw row diff --git a/ormar/models/newbasemodel.py b/ormar/models/newbasemodel.py index 72083d3..3f48ddf 100644 --- a/ormar/models/newbasemodel.py +++ b/ormar/models/newbasemodel.py @@ -136,7 +136,7 @@ class NewBaseModel(pydantic.BaseModel, ModelTableProxy, metaclass=ModelMetaclass def _extract_related_model_instead_of_field( self, item: str - ) -> Optional[Union[T, Sequence[T]]]: + ) -> Optional[Union["T", Sequence["T"]]]: alias = self.get_column_alias(item) if alias in self._orm: return self._orm.get(alias) @@ -173,7 +173,7 @@ class NewBaseModel(pydantic.BaseModel, ModelTableProxy, metaclass=ModelMetaclass def db_backend_name(cls) -> str: return cls.Meta.database._backend._dialect.name - def remove(self, name: T) -> None: + def remove(self, name: "T") -> None: self._orm.remove_parent(self, name) def dict( # noqa A003 diff --git a/ormar/queryset/queryset.py b/ormar/queryset/queryset.py index 5b58c55..749eb75 100644 --- a/ormar/queryset/queryset.py +++ b/ormar/queryset/queryset.py @@ -39,7 +39,7 @@ class QuerySet: def __get__( self, - instance: Union["QuerySet", "QuerysetProxy"], + instance: Optional[Union["QuerySet", "QuerysetProxy"]], owner: Union[Type["Model"], Type["QuerysetProxy"]], ) -> "QuerySet": if issubclass(owner, ormar.Model): diff --git a/ormar/relations/querysetproxy.py b/ormar/relations/querysetproxy.py index b9fb250..88c8dc1 100644 --- a/ormar/relations/querysetproxy.py +++ b/ormar/relations/querysetproxy.py @@ -28,28 +28,28 @@ class QuerysetProxy: def queryset(self, value: "QuerySet") -> None: self._queryset = value - def _assign_child_to_parent(self, child: Optional[T]) -> None: + def _assign_child_to_parent(self, child: Optional["T"]) -> None: if child: owner = self.relation._owner rel_name = owner.resolve_relation_name(owner, child) setattr(owner, rel_name, child) - def _register_related(self, child: Union[T, Sequence[Optional[T]]]) -> None: + def _register_related(self, child: Union["T", Sequence[Optional["T"]]]) -> None: if isinstance(child, list): for subchild in child: self._assign_child_to_parent(subchild) else: - assert isinstance(child, Model) + assert isinstance(child, ormar.Model) self._assign_child_to_parent(child) - async def create_through_instance(self, child: T) -> None: + async def create_through_instance(self, child: "T") -> None: queryset = ormar.QuerySet(model_cls=self.relation.through) owner_column = self.relation._owner.get_name() child_column = child.get_name() kwargs = {owner_column: self.relation._owner, child_column: child} await queryset.create(**kwargs) - async def delete_through_instance(self, child: T) -> None: + async def delete_through_instance(self, child: "T") -> None: queryset = ormar.QuerySet(model_cls=self.relation.through) owner_column = self.relation._owner.get_name() child_column = child.get_name() diff --git a/ormar/relations/relation.py b/ormar/relations/relation.py index 6520702..e09f00c 100644 --- a/ormar/relations/relation.py +++ b/ormar/relations/relation.py @@ -25,15 +25,15 @@ class Relation: self, manager: "RelationsManager", type_: RelationType, - to: Type[T], - through: Type[T] = None, + to: Type["T"], + through: Type["T"] = None, ) -> None: self.manager = manager self._owner: "Model" = manager.owner self._type: RelationType = type_ - self.to: Type[T] = to - self.through: Optional[Type[T]] = through - self.related_models: Optional[Union[RelationProxy, T]] = ( + self.to: Type["T"] = to + self.through: Optional[Type["T"]] = through + self.related_models: Optional[Union[RelationProxy, "T"]] = ( RelationProxy(relation=self) if type_ in (RelationType.REVERSE, RelationType.MULTIPLE) else None @@ -52,7 +52,7 @@ class Relation: self.related_models.pop(ind) return None - def add(self, child: T) -> None: + def add(self, child: "T") -> None: relation_name = self._owner.resolve_relation_name(self._owner, child) if self._type == RelationType.PRIMARY: self.related_models = child @@ -79,7 +79,7 @@ class Relation: self.related_models.pop(position) # type: ignore del self._owner.__dict__[relation_name][position] - def get(self) -> Optional[Union[List[T], T]]: + def get(self) -> Optional[Union[List["T"], "T"]]: return self.related_models def __repr__(self) -> str: # pragma no cover diff --git a/ormar/relations/relation_manager.py b/ormar/relations/relation_manager.py index 82a6887..0e36844 100644 --- a/ormar/relations/relation_manager.py +++ b/ormar/relations/relation_manager.py @@ -48,7 +48,7 @@ class RelationsManager: def __contains__(self, item: str) -> bool: return item in self._related_names - def get(self, name: str) -> Optional[Union[T, Sequence[T]]]: + def get(self, name: str) -> Optional[Union["T", Sequence["T"]]]: relation = self._relations.get(name, None) if relation is not None: return relation.get() diff --git a/tests/test_aliases.py b/tests/test_aliases.py index b48bb3f..b07e3af 100644 --- a/tests/test_aliases.py +++ b/tests/test_aliases.py @@ -15,10 +15,10 @@ class Child(ormar.Model): metadata = metadata database = database - id: ormar.Integer(name="child_id", primary_key=True) - first_name: ormar.String(name="fname", max_length=100) - last_name: ormar.String(name="lname", max_length=100) - born_year: ormar.Integer(name="year_born", nullable=True) + id = ormar.Integer(name="child_id", primary_key=True) + first_name = ormar.String(name="fname", max_length=100) + last_name = ormar.String(name="lname", max_length=100) + born_year = ormar.Integer(name="year_born", nullable=True) class ArtistChildren(ormar.Model): @@ -34,11 +34,13 @@ class Artist(ormar.Model): metadata = metadata database = database - id: ormar.Integer(name="artist_id", primary_key=True) - first_name: ormar.String(name="fname", max_length=100) - last_name: ormar.String(name="lname", max_length=100) - born_year: ormar.Integer(name="year") - children: ormar.ManyToMany(Child, through=ArtistChildren) + id = ormar.Integer(name="artist_id", primary_key=True) + first_name = ormar.String(name="fname", max_length=100) + last_name = ormar.String(name="lname", max_length=100) + born_year = ormar.Integer(name="year") + children = ormar.ManyToMany( + Child, through=ArtistChildren + ) class Album(ormar.Model): @@ -47,9 +49,9 @@ class Album(ormar.Model): metadata = metadata database = database - id: ormar.Integer(name="album_id", primary_key=True) - name: ormar.String(name="album_name", max_length=100) - artist: ormar.ForeignKey(Artist, name="artist_id") + id = ormar.Integer(name="album_id", primary_key=True) + name = ormar.String(name="album_name", max_length=100) + artist = ormar.ForeignKey(Artist, name="artist_id") @pytest.fixture(autouse=True, scope="module") diff --git a/tests/test_columns.py b/tests/test_columns.py index b2a7bd0..d0eb326 100644 --- a/tests/test_columns.py +++ b/tests/test_columns.py @@ -2,6 +2,7 @@ import datetime import os import databases +import pydantic import pytest import sqlalchemy @@ -22,14 +23,14 @@ class Example(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=200, default="aaa") - created: ormar.DateTime(default=datetime.datetime.now) - created_day: ormar.Date(default=datetime.date.today) - created_time: ormar.Time(default=time) - description: ormar.Text(nullable=True) - value: ormar.Float(nullable=True) - data: ormar.JSON(default={}) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=200, default="aaa") + created = ormar.DateTime(default=datetime.datetime.now) + created_day = ormar.Date(default=datetime.date.today) + created_time = ormar.Time(default=time) + description = ormar.Text(nullable=True) + value = ormar.Float(nullable=True) + data = ormar.JSON(default={}) @pytest.fixture(autouse=True, scope="module") diff --git a/tests/test_fastapi_docs.py b/tests/test_fastapi_docs.py index 4cb1df3..8ad0e56 100644 --- a/tests/test_fastapi_docs.py +++ b/tests/test_fastapi_docs.py @@ -38,8 +38,8 @@ class Category(ormar.Model): class Meta(LocalMeta): tablename = "categories" - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class ItemsXCategories(ormar.Model): @@ -51,9 +51,11 @@ class Item(ormar.Model): class Meta(LocalMeta): pass - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - categories: ormar.ManyToMany(Category, through=ItemsXCategories) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + categories = ormar.ManyToMany( + Category, through=ItemsXCategories + ) @pytest.fixture(autouse=True, scope="module") diff --git a/tests/test_fastapi_usage.py b/tests/test_fastapi_usage.py index fcbf479..ecf1a5f 100644 --- a/tests/test_fastapi_usage.py +++ b/tests/test_fastapi_usage.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import sqlalchemy from fastapi import FastAPI @@ -18,8 +20,8 @@ class Category(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Item(ormar.Model): @@ -28,9 +30,9 @@ class Item(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - category: ormar.ForeignKey(Category, nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + category = ormar.ForeignKey(Category, nullable=True) @app.post("/items/", response_model=Item) diff --git a/tests/test_foreign_keys.py b/tests/test_foreign_keys.py index b85493d..4fe836c 100644 --- a/tests/test_foreign_keys.py +++ b/tests/test_foreign_keys.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import pytest import sqlalchemy @@ -16,8 +18,8 @@ class Album(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id: int = ormar.Integer(primary_key=True) + name: str = ormar.String(max_length=100) class Track(ormar.Model): @@ -26,10 +28,10 @@ class Track(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - album: ormar.ForeignKey(Album) - title: ormar.String(max_length=100) - position: ormar.Integer() + id: int = ormar.Integer(primary_key=True) + album: Optional[Album] = ormar.ForeignKey(Album) + title: str = ormar.String(max_length=100) + position: int = ormar.Integer() class Cover(ormar.Model): @@ -38,9 +40,9 @@ class Cover(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - album: ormar.ForeignKey(Album, related_name="cover_pictures") - title: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + album = ormar.ForeignKey(Album, related_name="cover_pictures") + title = ormar.String(max_length=100) class Organisation(ormar.Model): @@ -49,8 +51,12 @@ class Organisation(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - ident: ormar.String(max_length=100, choices=["ACME Ltd", "Other ltd"]) + id = ormar.Integer(primary_key=True) + ident = ormar.String(max_length=100, choices=["ACME Ltd", "Other ltd"]) + + +class Organization(object): + pass class Team(ormar.Model): @@ -59,9 +65,9 @@ class Team(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - org: ormar.ForeignKey(Organisation) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + org = ormar.ForeignKey(Organisation) + name = ormar.String(max_length=100) class Member(ormar.Model): @@ -70,9 +76,9 @@ class Member(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - team: ormar.ForeignKey(Team) - email: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + team = ormar.ForeignKey(Team) + email = ormar.String(max_length=100) @pytest.fixture(autouse=True, scope="module") @@ -233,8 +239,8 @@ async def test_fk_filter(): tracks = ( await Track.objects.select_related("album") - .filter(album__name="Fantasies") - .all() + .filter(album__name="Fantasies") + .all() ) assert len(tracks) == 3 for track in tracks: @@ -242,8 +248,8 @@ async def test_fk_filter(): tracks = ( await Track.objects.select_related("album") - .filter(album__name__icontains="fan") - .all() + .filter(album__name__icontains="fan") + .all() ) assert len(tracks) == 3 for track in tracks: @@ -288,8 +294,8 @@ async def test_multiple_fk(): members = ( await Member.objects.select_related("team__org") - .filter(team__org__ident="ACME Ltd") - .all() + .filter(team__org__ident="ACME Ltd") + .all() ) assert len(members) == 4 for member in members: @@ -321,8 +327,8 @@ async def test_pk_filter(): tracks = ( await Track.objects.select_related("album") - .filter(position=2, album__name="Test") - .all() + .filter(position=2, album__name="Test") + .all() ) assert len(tracks) == 1 diff --git a/tests/test_many_to_many.py b/tests/test_many_to_many.py index fc97b0d..d4e78ad 100644 --- a/tests/test_many_to_many.py +++ b/tests/test_many_to_many.py @@ -1,4 +1,5 @@ import asyncio +from typing import List, Union, Optional import databases import pytest @@ -18,9 +19,9 @@ class Author(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - first_name: ormar.String(max_length=80) - last_name: ormar.String(max_length=80) + id = ormar.Integer(primary_key=True) + first_name = ormar.String(max_length=80) + last_name = ormar.String(max_length=80) class Category(ormar.Model): @@ -29,8 +30,8 @@ class Category(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=40) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=40) class PostCategory(ormar.Model): @@ -46,10 +47,12 @@ class Post(ormar.Model): database = database metadata = metadata - id: ormar.Integer(primary_key=True) - title: ormar.String(max_length=200) - categories: ormar.ManyToMany(Category, through=PostCategory) - author: ormar.ForeignKey(Author) + id = ormar.Integer(primary_key=True) + title = ormar.String(max_length=200) + categories = ormar.ManyToMany( + Category, through=PostCategory + ) + author= ormar.ForeignKey(Author) @pytest.fixture(scope="module") diff --git a/tests/test_model_definition.py b/tests/test_model_definition.py index 2f64259..dd3b717 100644 --- a/tests/test_model_definition.py +++ b/tests/test_model_definition.py @@ -1,13 +1,17 @@ +# type: ignore +import asyncio import datetime import decimal import pydantic import pytest import sqlalchemy +import typing -import ormar.fields as fields +import ormar from ormar.exceptions import ModelDefinitionError from ormar.models import Model +from tests.settings import DATABASE_URL metadata = sqlalchemy.MetaData() @@ -17,18 +21,18 @@ class ExampleModel(Model): tablename = "example" metadata = metadata - test: fields.Integer(primary_key=True) - test_string: fields.String(max_length=250) - test_text: fields.Text(default="") - test_bool: fields.Boolean(nullable=False) - test_float: fields.Float() = None - test_datetime: fields.DateTime(default=datetime.datetime.now) - test_date: fields.Date(default=datetime.date.today) - test_time: fields.Time(default=datetime.time) - test_json: fields.JSON(default={}) - test_bigint: fields.BigInteger(default=0) - test_decimal: fields.Decimal(scale=10, precision=2) - test_decimal2: fields.Decimal(max_digits=10, decimal_places=2) + test = ormar.Integer(primary_key=True) + test_string = ormar.String(max_length=250) + test_text = ormar.Text(default="") + test_bool = ormar.Boolean(nullable=False) + test_float: ormar.Float() = None # type: ignore + test_datetime = ormar.DateTime(default=datetime.datetime.now) + test_date = ormar.Date(default=datetime.date.today) + test_time = ormar.Time(default=datetime.time) + test_json = ormar.JSON(default={}) + test_bigint = ormar.BigInteger(default=0) + test_decimal = ormar.Decimal(scale=10, precision=2) + test_decimal2 = ormar.Decimal(max_digits=10, decimal_places=2) fields_to_check = [ @@ -46,11 +50,26 @@ fields_to_check = [ class ExampleModel2(Model): class Meta: - tablename = "example2" + tablename = "examples" metadata = metadata - test: fields.Integer(primary_key=True) - test_string: fields.String(max_length=250) + test = ormar.Integer(primary_key=True) + test_string = ormar.String(max_length=250) + + +@pytest.fixture(scope="module") +def event_loop(): + loop = asyncio.get_event_loop() + yield loop + loop.close() + + +@pytest.fixture(autouse=True, scope="module") +async def create_test_database(): + engine = sqlalchemy.create_engine(DATABASE_URL) + metadata.create_all(engine) + yield + metadata.drop_all(engine) @pytest.fixture() @@ -117,62 +136,64 @@ def test_sqlalchemy_table_is_created(example): assert all([field in example.Meta.table.columns for field in fields_to_check]) -def test_no_pk_in_model_definition(): - with pytest.raises(ModelDefinitionError): - - class ExampleModel2(Model): +@typing.no_type_check +def test_no_pk_in_model_definition(): # type: ignore + with pytest.raises(ModelDefinitionError): # type: ignore + class ExampleModel2(Model): # type: ignore class Meta: - tablename = "example3" + tablename = "example2" metadata = metadata - test_string: fields.String(max_length=250) + test_string = ormar.String(max_length=250) # type: ignore +@typing.no_type_check def test_two_pks_in_model_definition(): with pytest.raises(ModelDefinitionError): - + @typing.no_type_check class ExampleModel2(Model): class Meta: tablename = "example3" metadata = metadata - id: fields.Integer(primary_key=True) - test_string: fields.String(max_length=250, primary_key=True) + id = ormar.Integer(primary_key=True) + test_string = ormar.String(max_length=250, primary_key=True) +@typing.no_type_check def test_setting_pk_column_as_pydantic_only_in_model_definition(): with pytest.raises(ModelDefinitionError): - class ExampleModel2(Model): class Meta: tablename = "example4" metadata = metadata - test: fields.Integer(primary_key=True, pydantic_only=True) + test = ormar.Integer(primary_key=True, pydantic_only=True) +@typing.no_type_check def test_decimal_error_in_model_definition(): with pytest.raises(ModelDefinitionError): - class ExampleModel2(Model): class Meta: tablename = "example5" metadata = metadata - test: fields.Decimal(primary_key=True) + test = ormar.Decimal(primary_key=True) +@typing.no_type_check def test_string_error_in_model_definition(): with pytest.raises(ModelDefinitionError): - class ExampleModel2(Model): class Meta: tablename = "example6" metadata = metadata - test: fields.String(primary_key=True) + test = ormar.String(primary_key=True) +@typing.no_type_check def test_json_conversion_in_model(): with pytest.raises(pydantic.ValidationError): ExampleModel( diff --git a/tests/test_models.py b/tests/test_models.py index cc783e3..067e0b0 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -22,8 +22,8 @@ class JsonSample(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - test_json: ormar.JSON(nullable=True) + id = ormar.Integer(primary_key=True) + test_json= ormar.JSON(nullable=True) class UUIDSample(ormar.Model): @@ -32,8 +32,8 @@ class UUIDSample(ormar.Model): metadata = metadata database = database - id: ormar.UUID(primary_key=True, default=uuid.uuid4) - test_text: ormar.Text() + id= ormar.UUID(primary_key=True, default=uuid.uuid4) + test_text = ormar.Text() class User(ormar.Model): @@ -42,8 +42,8 @@ class User(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100, default="") + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100, default="") class Product(ormar.Model): @@ -52,11 +52,11 @@ class Product(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - rating: ormar.Integer(minimum=1, maximum=5) - in_stock: ormar.Boolean(default=False) - last_delivery: ormar.Date(default=datetime.now) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + rating = ormar.Integer(minimum=1, maximum=5) + in_stock= ormar.Boolean(default=False) + last_delivery= ormar.Date(default=datetime.now) country_name_choices = ("Canada", "Algeria", "United States") @@ -70,12 +70,12 @@ class Country(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String( + id = ormar.Integer(primary_key=True) + name = ormar.String( max_length=9, choices=country_name_choices, default="Canada", ) - taxed: ormar.Boolean(choices=country_taxed_choices, default=True) - country_code: ormar.Integer( + taxed= ormar.Boolean(choices=country_taxed_choices, default=True) + country_code = ormar.Integer( minimum=0, maximum=1000, choices=country_country_code_choices, default=1 ) diff --git a/tests/test_more_reallife_fastapi.py b/tests/test_more_reallife_fastapi.py index b538b5c..1ad7425 100644 --- a/tests/test_more_reallife_fastapi.py +++ b/tests/test_more_reallife_fastapi.py @@ -1,4 +1,4 @@ -from typing import List +from typing import List, Optional import databases import pytest @@ -35,8 +35,8 @@ class Category(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Item(ormar.Model): @@ -45,9 +45,9 @@ class Item(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - category: ormar.ForeignKey(Category, nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + category = ormar.ForeignKey(Category, nullable=True) @pytest.fixture(autouse=True, scope="module") diff --git a/tests/test_more_same_table_joins.py b/tests/test_more_same_table_joins.py index 0492d91..d0b9859 100644 --- a/tests/test_more_same_table_joins.py +++ b/tests/test_more_same_table_joins.py @@ -1,4 +1,5 @@ import asyncio +from typing import Optional import databases import pytest @@ -17,8 +18,8 @@ class Department(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True, autoincrement=False) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True, autoincrement=False) + name = ormar.String(max_length=100) class SchoolClass(ormar.Model): @@ -27,8 +28,8 @@ class SchoolClass(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Category(ormar.Model): @@ -37,9 +38,9 @@ class Category(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - department: ormar.ForeignKey(Department, nullable=False) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + department= ormar.ForeignKey(Department, nullable=False) class Student(ormar.Model): @@ -48,10 +49,10 @@ class Student(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - schoolclass: ormar.ForeignKey(SchoolClass) - category: ormar.ForeignKey(Category, nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + schoolclass= ormar.ForeignKey(SchoolClass) + category= ormar.ForeignKey(Category, nullable=True) class Teacher(ormar.Model): @@ -60,10 +61,10 @@ class Teacher(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - schoolclass: ormar.ForeignKey(SchoolClass) - category: ormar.ForeignKey(Category, nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + schoolclass= ormar.ForeignKey(SchoolClass) + category= ormar.ForeignKey(Category, nullable=True) @pytest.fixture(scope="module") diff --git a/tests/test_new_annotation_style.py b/tests/test_new_annotation_style.py index 9a665cc..54a20cf 100644 --- a/tests/test_new_annotation_style.py +++ b/tests/test_new_annotation_style.py @@ -18,8 +18,8 @@ class Album(ormar.Model): metadata = metadata database = database - id: int = ormar.Integer(primary_key=True) - name: str = ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Track(ormar.Model): @@ -28,10 +28,10 @@ class Track(ormar.Model): metadata = metadata database = database - id: int = ormar.Integer(primary_key=True) - album: Optional[Album] = ormar.ForeignKey(Album) - title: str = ormar.String(max_length=100) - position: int = ormar.Integer() + id = ormar.Integer(primary_key=True) + album= ormar.ForeignKey(Album) + title = ormar.String(max_length=100) + position = ormar.Integer() class Cover(ormar.Model): @@ -40,9 +40,9 @@ class Cover(ormar.Model): metadata = metadata database = database - id: int = ormar.Integer(primary_key=True) - album: Album = ormar.ForeignKey(Album, related_name="cover_pictures") - title: str = ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + album= ormar.ForeignKey(Album, related_name="cover_pictures") + title = ormar.String(max_length=100) class Organisation(ormar.Model): @@ -51,8 +51,8 @@ class Organisation(ormar.Model): metadata = metadata database = database - id: int = ormar.Integer(primary_key=True) - ident: str = ormar.String(max_length=100, choices=["ACME Ltd", "Other ltd"]) + id = ormar.Integer(primary_key=True) + ident = ormar.String(max_length=100, choices=["ACME Ltd", "Other ltd"]) class Team(ormar.Model): @@ -61,9 +61,9 @@ class Team(ormar.Model): metadata = metadata database = database - id: int = ormar.Integer(primary_key=True) - org: Optional[Organisation] = ormar.ForeignKey(Organisation) - name: str = ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + org= ormar.ForeignKey(Organisation) + name = ormar.String(max_length=100) class Member(ormar.Model): @@ -72,9 +72,9 @@ class Member(ormar.Model): metadata = metadata database = database - id: int = ormar.Integer(primary_key=True) - team: Optional[Team] = ormar.ForeignKey(Team) - email: str = ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + team= ormar.ForeignKey(Team) + email = ormar.String(max_length=100) @pytest.fixture(autouse=True, scope="module") diff --git a/tests/test_non_integer_pkey.py b/tests/test_non_integer_pkey.py index d601e10..0b3d8d1 100644 --- a/tests/test_non_integer_pkey.py +++ b/tests/test_non_integer_pkey.py @@ -21,8 +21,8 @@ class Model(ormar.Model): metadata = metadata database = database - id: ormar.String(primary_key=True, default=key, max_length=8) - name: ormar.String(max_length=32) + id = ormar.String(primary_key=True, default=key, max_length=8) + name = ormar.String(max_length=32) @pytest.fixture(autouse=True, scope="function") diff --git a/tests/test_queryset_level_methods.py b/tests/test_queryset_level_methods.py index af8385e..1e986b5 100644 --- a/tests/test_queryset_level_methods.py +++ b/tests/test_queryset_level_methods.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import pytest import sqlalchemy @@ -16,10 +18,10 @@ class Book(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - title: ormar.String(max_length=200) - author: ormar.String(max_length=100) - genre: ormar.String( + id = ormar.Integer(primary_key=True) + title = ormar.String(max_length=200) + author = ormar.String(max_length=100) + genre = ormar.String( max_length=100, default="Fiction", choices=["Fiction", "Adventure", "Historic", "Fantasy"], @@ -32,9 +34,9 @@ class ToDo(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - text: ormar.String(max_length=500) - completed: ormar.Boolean(default=False) + id = ormar.Integer(primary_key=True) + text = ormar.String(max_length=500) + completed= ormar.Boolean(default=False) class Category(ormar.Model): @@ -43,8 +45,8 @@ class Category(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=500) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=500) class Note(ormar.Model): @@ -53,9 +55,9 @@ class Note(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - text: ormar.String(max_length=500) - category: ormar.ForeignKey(Category) + id = ormar.Integer(primary_key=True) + text = ormar.String(max_length=500) + category= ormar.ForeignKey(Category) @pytest.fixture(autouse=True, scope="module") diff --git a/tests/test_same_table_joins.py b/tests/test_same_table_joins.py index 33d2677..5d3169b 100644 --- a/tests/test_same_table_joins.py +++ b/tests/test_same_table_joins.py @@ -1,4 +1,5 @@ import asyncio +from typing import Optional import databases import pytest @@ -17,8 +18,8 @@ class Department(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True, autoincrement=False) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True, autoincrement=False) + name = ormar.String(max_length=100) class SchoolClass(ormar.Model): @@ -27,9 +28,9 @@ class SchoolClass(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - department: ormar.ForeignKey(Department, nullable=False) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + department= ormar.ForeignKey(Department, nullable=False) class Category(ormar.Model): @@ -38,8 +39,8 @@ class Category(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) class Student(ormar.Model): @@ -48,10 +49,10 @@ class Student(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - schoolclass: ormar.ForeignKey(SchoolClass) - category: ormar.ForeignKey(Category, nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + schoolclass= ormar.ForeignKey(SchoolClass) + category= ormar.ForeignKey(Category, nullable=True) class Teacher(ormar.Model): @@ -60,10 +61,10 @@ class Teacher(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - schoolclass: ormar.ForeignKey(SchoolClass) - category: ormar.ForeignKey(Category, nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + schoolclass= ormar.ForeignKey(SchoolClass) + category= ormar.ForeignKey(Category, nullable=True) @pytest.fixture(scope="module") diff --git a/tests/test_selecting_subset_of_columns.py b/tests/test_selecting_subset_of_columns.py index dee9785..fc73109 100644 --- a/tests/test_selecting_subset_of_columns.py +++ b/tests/test_selecting_subset_of_columns.py @@ -1,3 +1,5 @@ +from typing import Optional + import databases import pydantic import pytest @@ -16,9 +18,9 @@ class Company(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100, nullable=False) - founded: ormar.Integer(nullable=True) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100, nullable=False) + founded = ormar.Integer(nullable=True) class Car(ormar.Model): @@ -27,13 +29,13 @@ class Car(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - manufacturer: ormar.ForeignKey(Company) - name: ormar.String(max_length=100) - year: ormar.Integer(nullable=True) - gearbox_type: ormar.String(max_length=20, nullable=True) - gears: ormar.Integer(nullable=True) - aircon_type: ormar.String(max_length=20, nullable=True) + id = ormar.Integer(primary_key=True) + manufacturer= ormar.ForeignKey(Company) + name = ormar.String(max_length=100) + year = ormar.Integer(nullable=True) + gearbox_type = ormar.String(max_length=20, nullable=True) + gears = ormar.Integer(nullable=True) + aircon_type = ormar.String(max_length=20, nullable=True) @pytest.fixture(autouse=True, scope="module") diff --git a/tests/test_server_default.py b/tests/test_server_default.py index 4c4db66..dbee490 100644 --- a/tests/test_server_default.py +++ b/tests/test_server_default.py @@ -20,11 +20,11 @@ class Product(ormar.Model): metadata = metadata database = database - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - company: ormar.String(max_length=200, server_default="Acme") - sort_order: ormar.Integer(server_default=text("10")) - created: ormar.DateTime(server_default=func.now()) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + company = ormar.String(max_length=200, server_default="Acme") + sort_order = ormar.Integer(server_default=text("10")) + created= ormar.DateTime(server_default=func.now()) @pytest.fixture(scope="module") diff --git a/tests/test_unique_constraints.py b/tests/test_unique_constraints.py index 93dd9ba..e39cbbc 100644 --- a/tests/test_unique_constraints.py +++ b/tests/test_unique_constraints.py @@ -21,9 +21,9 @@ class Product(ormar.Model): database = database constraints = [ormar.UniqueColumns("name", "company")] - id: ormar.Integer(primary_key=True) - name: ormar.String(max_length=100) - company: ormar.String(max_length=200) + id = ormar.Integer(primary_key=True) + name = ormar.String(max_length=100) + company = ormar.String(max_length=200) @pytest.fixture(scope="module")