liniting, black, mypy fixes
This commit is contained in:
@ -1,4 +1,4 @@
|
|||||||
from typing import Any, List, Optional, TYPE_CHECKING, Type, Union, Sequence
|
from typing import Any, List, Optional, Sequence, TYPE_CHECKING, Type, Union
|
||||||
|
|
||||||
from ormar.fields import BaseField
|
from ormar.fields import BaseField
|
||||||
from ormar.fields.foreign_key import ForeignKeyField
|
from ormar.fields.foreign_key import ForeignKeyField
|
||||||
@ -10,13 +10,13 @@ REF_PREFIX = "#/components/schemas/"
|
|||||||
|
|
||||||
|
|
||||||
def ManyToMany(
|
def ManyToMany(
|
||||||
to: Type["Model"],
|
to: Type["Model"],
|
||||||
through: Type["Model"],
|
through: Type["Model"],
|
||||||
*,
|
*,
|
||||||
name: str = None,
|
name: str = None,
|
||||||
unique: bool = False,
|
unique: bool = False,
|
||||||
virtual: bool = False,
|
virtual: bool = False,
|
||||||
**kwargs: Any
|
**kwargs: Any
|
||||||
) -> Type["ManyToManyField"]:
|
) -> Type["ManyToManyField"]:
|
||||||
to_field = to.Meta.model_fields[to.Meta.pkname]
|
to_field = to.Meta.model_fields[to.Meta.pkname]
|
||||||
related_name = kwargs.pop("related_name", None)
|
related_name = kwargs.pop("related_name", None)
|
||||||
@ -50,7 +50,8 @@ def ManyToMany(
|
|||||||
class ManyToManyField(ForeignKeyField):
|
class ManyToManyField(ForeignKeyField):
|
||||||
through: Type["Model"]
|
through: Type["Model"]
|
||||||
|
|
||||||
if TYPE_CHECKING: # pragma nocover
|
if TYPE_CHECKING: # noqa: C901; pragma nocover
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def add(item: "Model") -> None:
|
async def add(item: "Model") -> None:
|
||||||
pass
|
pass
|
||||||
@ -62,7 +63,7 @@ class ManyToManyField(ForeignKeyField):
|
|||||||
from ormar import QuerySet
|
from ormar import QuerySet
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def filter(**kwargs: Any) -> "QuerySet": # noqa: A003
|
def filter(**kwargs: Any) -> "QuerySet": # noqa: A003, A001
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -70,15 +71,15 @@ class ManyToManyField(ForeignKeyField):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def exists(self) -> bool:
|
async def exists() -> bool:
|
||||||
return await self.queryset.exists()
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def count(self) -> int:
|
async def count() -> int:
|
||||||
return await self.queryset.count()
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def clear(self) -> int:
|
async def clear() -> int:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -86,21 +87,21 @@ class ManyToManyField(ForeignKeyField):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def offset(self, offset: int) -> "QuerySet":
|
def offset(offset: int) -> "QuerySet":
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def first(self, **kwargs: Any) -> "Model":
|
async def first(**kwargs: Any) -> "Model":
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get(self, **kwargs: Any) -> "Model":
|
async def get(**kwargs: Any) -> "Model":
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def all(self, **kwargs: Any) -> Sequence[Optional["Model"]]: # noqa: A003
|
async def all(**kwargs: Any) -> Sequence[Optional["Model"]]: # noqa: A003, A001
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def create(self, **kwargs: Any) -> "Model":
|
async def create(**kwargs: Any) -> "Model":
|
||||||
pass
|
pass
|
||||||
|
|||||||
@ -12,7 +12,7 @@ from ormar.fields.base import BaseField # noqa I101
|
|||||||
|
|
||||||
|
|
||||||
def is_field_nullable(
|
def is_field_nullable(
|
||||||
nullable: Optional[bool], default: Any, server_default: Any
|
nullable: Optional[bool], default: Any, server_default: Any
|
||||||
) -> bool:
|
) -> bool:
|
||||||
if nullable is None:
|
if nullable is None:
|
||||||
return default is not None or server_default is not None
|
return default is not None or server_default is not None
|
||||||
@ -63,15 +63,15 @@ class String(ModelFieldFactory, str):
|
|||||||
_pydantic_type = pydantic.ConstrainedStr
|
_pydantic_type = pydantic.ConstrainedStr
|
||||||
|
|
||||||
def __new__( # type: ignore # noqa CFQ002
|
def __new__( # type: ignore # noqa CFQ002
|
||||||
cls,
|
cls,
|
||||||
*,
|
*,
|
||||||
allow_blank: bool = True,
|
allow_blank: bool = True,
|
||||||
strip_whitespace: bool = False,
|
strip_whitespace: bool = False,
|
||||||
min_length: int = None,
|
min_length: int = None,
|
||||||
max_length: int = None,
|
max_length: int = None,
|
||||||
curtail_length: int = None,
|
curtail_length: int = None,
|
||||||
regex: str = None,
|
regex: str = None,
|
||||||
**kwargs: Any
|
**kwargs: Any
|
||||||
) -> Type[BaseField]: # type: ignore
|
) -> Type[BaseField]: # type: ignore
|
||||||
kwargs = {
|
kwargs = {
|
||||||
**kwargs,
|
**kwargs,
|
||||||
@ -102,12 +102,12 @@ class Integer(ModelFieldFactory, int):
|
|||||||
_pydantic_type = pydantic.ConstrainedInt
|
_pydantic_type = pydantic.ConstrainedInt
|
||||||
|
|
||||||
def __new__( # type: ignore
|
def __new__( # type: ignore
|
||||||
cls,
|
cls,
|
||||||
*,
|
*,
|
||||||
minimum: int = None,
|
minimum: int = None,
|
||||||
maximum: int = None,
|
maximum: int = None,
|
||||||
multiple_of: int = None,
|
multiple_of: int = None,
|
||||||
**kwargs: Any
|
**kwargs: Any
|
||||||
) -> Type[BaseField]:
|
) -> Type[BaseField]:
|
||||||
autoincrement = kwargs.pop("autoincrement", None)
|
autoincrement = kwargs.pop("autoincrement", None)
|
||||||
autoincrement = (
|
autoincrement = (
|
||||||
@ -137,7 +137,7 @@ class Text(ModelFieldFactory, str):
|
|||||||
_pydantic_type = pydantic.ConstrainedStr
|
_pydantic_type = pydantic.ConstrainedStr
|
||||||
|
|
||||||
def __new__( # type: ignore
|
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]:
|
) -> Type[BaseField]:
|
||||||
kwargs = {
|
kwargs = {
|
||||||
**kwargs,
|
**kwargs,
|
||||||
@ -160,12 +160,12 @@ class Float(ModelFieldFactory, float):
|
|||||||
_pydantic_type = pydantic.ConstrainedFloat
|
_pydantic_type = pydantic.ConstrainedFloat
|
||||||
|
|
||||||
def __new__( # type: ignore
|
def __new__( # type: ignore
|
||||||
cls,
|
cls,
|
||||||
*,
|
*,
|
||||||
minimum: float = None,
|
minimum: float = None,
|
||||||
maximum: float = None,
|
maximum: float = None,
|
||||||
multiple_of: int = None,
|
multiple_of: int = None,
|
||||||
**kwargs: Any
|
**kwargs: Any
|
||||||
) -> Type[BaseField]:
|
) -> Type[BaseField]:
|
||||||
kwargs = {
|
kwargs = {
|
||||||
**kwargs,
|
**kwargs,
|
||||||
@ -234,12 +234,12 @@ class BigInteger(Integer, int):
|
|||||||
_pydantic_type = pydantic.ConstrainedInt
|
_pydantic_type = pydantic.ConstrainedInt
|
||||||
|
|
||||||
def __new__( # type: ignore
|
def __new__( # type: ignore
|
||||||
cls,
|
cls,
|
||||||
*,
|
*,
|
||||||
minimum: int = None,
|
minimum: int = None,
|
||||||
maximum: int = None,
|
maximum: int = None,
|
||||||
multiple_of: int = None,
|
multiple_of: int = None,
|
||||||
**kwargs: Any
|
**kwargs: Any
|
||||||
) -> Type[BaseField]:
|
) -> Type[BaseField]:
|
||||||
autoincrement = kwargs.pop("autoincrement", None)
|
autoincrement = kwargs.pop("autoincrement", None)
|
||||||
autoincrement = (
|
autoincrement = (
|
||||||
@ -269,16 +269,16 @@ class Decimal(ModelFieldFactory, decimal.Decimal):
|
|||||||
_pydantic_type = pydantic.ConstrainedDecimal
|
_pydantic_type = pydantic.ConstrainedDecimal
|
||||||
|
|
||||||
def __new__( # type: ignore # noqa CFQ002
|
def __new__( # type: ignore # noqa CFQ002
|
||||||
cls,
|
cls,
|
||||||
*,
|
*,
|
||||||
minimum: float = None,
|
minimum: float = None,
|
||||||
maximum: float = None,
|
maximum: float = None,
|
||||||
multiple_of: int = None,
|
multiple_of: int = None,
|
||||||
precision: int = None,
|
precision: int = None,
|
||||||
scale: int = None,
|
scale: int = None,
|
||||||
max_digits: int = None,
|
max_digits: int = None,
|
||||||
decimal_places: int = None,
|
decimal_places: int = None,
|
||||||
**kwargs: Any
|
**kwargs: Any
|
||||||
) -> Type[BaseField]:
|
) -> Type[BaseField]:
|
||||||
kwargs = {
|
kwargs = {
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|||||||
@ -42,7 +42,7 @@ def register_relation_on_build(table_name: str, field: Type[ForeignKeyField]) ->
|
|||||||
|
|
||||||
|
|
||||||
def register_many_to_many_relation_on_build(
|
def register_many_to_many_relation_on_build(
|
||||||
table_name: str, field: Type[ManyToManyField]
|
table_name: str, field: Type[ManyToManyField]
|
||||||
) -> None:
|
) -> None:
|
||||||
alias_manager.add_relation_type(field.through.Meta.tablename, table_name)
|
alias_manager.add_relation_type(field.through.Meta.tablename, table_name)
|
||||||
alias_manager.add_relation_type(
|
alias_manager.add_relation_type(
|
||||||
@ -51,11 +51,11 @@ def register_many_to_many_relation_on_build(
|
|||||||
|
|
||||||
|
|
||||||
def reverse_field_not_already_registered(
|
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:
|
) -> bool:
|
||||||
return (
|
return (
|
||||||
child_model_name not in parent_model.__fields__
|
child_model_name not in parent_model.__fields__
|
||||||
and child.get_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
|
parent_model = model_field.to
|
||||||
child = model
|
child = model
|
||||||
if reverse_field_not_already_registered(
|
if reverse_field_not_already_registered(
|
||||||
child, child_model_name, parent_model
|
child, child_model_name, parent_model
|
||||||
):
|
):
|
||||||
register_reverse_model_fields(
|
register_reverse_model_fields(
|
||||||
parent_model, child, child_model_name, model_field
|
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(
|
def register_reverse_model_fields(
|
||||||
model: Type["Model"],
|
model: Type["Model"],
|
||||||
child: Type["Model"],
|
child: Type["Model"],
|
||||||
child_model_name: str,
|
child_model_name: str,
|
||||||
model_field: Type["ForeignKeyField"],
|
model_field: Type["ForeignKeyField"],
|
||||||
) -> None:
|
) -> None:
|
||||||
if issubclass(model_field, ManyToManyField):
|
if issubclass(model_field, ManyToManyField):
|
||||||
model.Meta.model_fields[child_model_name] = ManyToMany(
|
model.Meta.model_fields[child_model_name] = ManyToMany(
|
||||||
@ -92,7 +92,7 @@ def register_reverse_model_fields(
|
|||||||
|
|
||||||
|
|
||||||
def adjust_through_many_to_many_model(
|
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:
|
) -> None:
|
||||||
model_field.through.Meta.model_fields[model.get_name()] = ForeignKey(
|
model_field.through.Meta.model_fields[model.get_name()] = ForeignKey(
|
||||||
model, name=model.get_name(), ondelete="CASCADE"
|
model, name=model.get_name(), ondelete="CASCADE"
|
||||||
@ -109,7 +109,7 @@ def adjust_through_many_to_many_model(
|
|||||||
|
|
||||||
|
|
||||||
def create_pydantic_field(
|
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:
|
) -> None:
|
||||||
model_field.through.__fields__[field_name] = ModelField(
|
model_field.through.__fields__[field_name] = ModelField(
|
||||||
name=field_name,
|
name=field_name,
|
||||||
@ -121,7 +121,7 @@ def create_pydantic_field(
|
|||||||
|
|
||||||
|
|
||||||
def create_and_append_m2m_fk(
|
def create_and_append_m2m_fk(
|
||||||
model: Type["Model"], model_field: Type[ManyToManyField]
|
model: Type["Model"], model_field: Type[ManyToManyField]
|
||||||
) -> None:
|
) -> None:
|
||||||
column = sqlalchemy.Column(
|
column = sqlalchemy.Column(
|
||||||
model.get_name(),
|
model.get_name(),
|
||||||
@ -137,7 +137,7 @@ def create_and_append_m2m_fk(
|
|||||||
|
|
||||||
|
|
||||||
def check_pk_column_validity(
|
def check_pk_column_validity(
|
||||||
field_name: str, field: BaseField, pkname: Optional[str]
|
field_name: str, field: BaseField, pkname: Optional[str]
|
||||||
) -> Optional[str]:
|
) -> Optional[str]:
|
||||||
if pkname is not None:
|
if pkname is not None:
|
||||||
raise ModelDefinitionError("Only one primary key column is allowed.")
|
raise ModelDefinitionError("Only one primary key column is allowed.")
|
||||||
@ -147,7 +147,7 @@ def check_pk_column_validity(
|
|||||||
|
|
||||||
|
|
||||||
def sqlalchemy_columns_from_model_fields(
|
def sqlalchemy_columns_from_model_fields(
|
||||||
model_fields: Dict, table_name: str
|
model_fields: Dict, table_name: str
|
||||||
) -> Tuple[Optional[str], List[sqlalchemy.Column]]:
|
) -> Tuple[Optional[str], List[sqlalchemy.Column]]:
|
||||||
columns = []
|
columns = []
|
||||||
pkname = None
|
pkname = None
|
||||||
@ -161,9 +161,9 @@ def sqlalchemy_columns_from_model_fields(
|
|||||||
if field.primary_key:
|
if field.primary_key:
|
||||||
pkname = check_pk_column_validity(field_name, field, pkname)
|
pkname = check_pk_column_validity(field_name, field, pkname)
|
||||||
if (
|
if (
|
||||||
not field.pydantic_only
|
not field.pydantic_only
|
||||||
and not field.virtual
|
and not field.virtual
|
||||||
and not issubclass(field, ManyToManyField)
|
and not issubclass(field, ManyToManyField)
|
||||||
):
|
):
|
||||||
columns.append(field.get_column(field_name))
|
columns.append(field.get_column(field_name))
|
||||||
register_relation_in_alias_manager(table_name, field)
|
register_relation_in_alias_manager(table_name, field)
|
||||||
@ -171,7 +171,7 @@ def sqlalchemy_columns_from_model_fields(
|
|||||||
|
|
||||||
|
|
||||||
def register_relation_in_alias_manager(
|
def register_relation_in_alias_manager(
|
||||||
table_name: str, field: Type[ForeignKeyField]
|
table_name: str, field: Type[ForeignKeyField]
|
||||||
) -> None:
|
) -> None:
|
||||||
if issubclass(field, ManyToManyField):
|
if issubclass(field, ManyToManyField):
|
||||||
register_many_to_many_relation_on_build(table_name, field)
|
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(
|
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:
|
) -> dict:
|
||||||
curr_def_value = attrs.get(field_name, ormar.Undefined)
|
curr_def_value = attrs.get(field_name, ormar.Undefined)
|
||||||
if lenient_issubclass(curr_def_value, ormar.fields.BaseField):
|
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(
|
def check_if_field_annotation_or_value_is_ormar(
|
||||||
field: Any, field_name: str, attrs: Dict
|
field: Any, field_name: str, attrs: Dict
|
||||||
) -> bool:
|
) -> bool:
|
||||||
return lenient_issubclass(field, BaseField) or issubclass(
|
return lenient_issubclass(field, BaseField) or issubclass(
|
||||||
attrs.get(field_name, type), BaseField
|
attrs.get(field_name, type), BaseField
|
||||||
@ -201,15 +201,21 @@ def check_if_field_annotation_or_value_is_ormar(
|
|||||||
|
|
||||||
|
|
||||||
def extract_field_from_annotation_or_value(
|
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]:
|
) -> Type[ormar.fields.BaseField]:
|
||||||
return field if lenient_issubclass(field, BaseField) else attrs.get(field_name)
|
return field if lenient_issubclass(field, BaseField) else attrs.get(field_name)
|
||||||
|
|
||||||
|
|
||||||
def populate_pydantic_default_values(attrs: Dict) -> Tuple[Dict, Dict]:
|
def populate_pydantic_default_values(attrs: Dict) -> Tuple[Dict, Dict]:
|
||||||
model_fields = {}
|
model_fields = {}
|
||||||
potential_fields = {k: v for k, v in attrs["__annotations__"].items() if lenient_issubclass(v, BaseField)}
|
potential_fields = {
|
||||||
potential_fields.update({k: v for k, v in attrs.items() if lenient_issubclass(v, BaseField)})
|
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():
|
for field_name, field in potential_fields.items():
|
||||||
# ormar fields can be used as annotation or as default value
|
# ormar fields can be used as annotation or as default value
|
||||||
if check_if_field_annotation_or_value_is_ormar(field, field_name, attrs):
|
if check_if_field_annotation_or_value_is_ormar(field, field_name, attrs):
|
||||||
@ -226,17 +232,15 @@ def populate_pydantic_default_values(attrs: Dict) -> Tuple[Dict, Dict]:
|
|||||||
return attrs, model_fields
|
return attrs, model_fields
|
||||||
|
|
||||||
|
|
||||||
def extract_annotations_and_default_vals(
|
def extract_annotations_and_default_vals(attrs: dict) -> Tuple[Dict, Dict]:
|
||||||
attrs: dict
|
key = "__annotations__"
|
||||||
) -> Tuple[Dict, Dict]:
|
|
||||||
key = '__annotations__'
|
|
||||||
attrs[key] = attrs.get(key, {})
|
attrs[key] = attrs.get(key, {})
|
||||||
attrs, model_fields = populate_pydantic_default_values(attrs)
|
attrs, model_fields = populate_pydantic_default_values(attrs)
|
||||||
return attrs, model_fields
|
return attrs, model_fields
|
||||||
|
|
||||||
|
|
||||||
def populate_meta_tablename_columns_and_pk(
|
def populate_meta_tablename_columns_and_pk(
|
||||||
name: str, new_model: Type["Model"]
|
name: str, new_model: Type["Model"]
|
||||||
) -> Type["Model"]:
|
) -> Type["Model"]:
|
||||||
tablename = name.lower() + "s"
|
tablename = name.lower() + "s"
|
||||||
new_model.Meta.tablename = (
|
new_model.Meta.tablename = (
|
||||||
@ -262,7 +266,7 @@ def populate_meta_tablename_columns_and_pk(
|
|||||||
|
|
||||||
|
|
||||||
def populate_meta_sqlalchemy_table_if_required(
|
def populate_meta_sqlalchemy_table_if_required(
|
||||||
new_model: Type["Model"],
|
new_model: Type["Model"],
|
||||||
) -> Type["Model"]:
|
) -> Type["Model"]:
|
||||||
if not hasattr(new_model.Meta, "table"):
|
if not hasattr(new_model.Meta, "table"):
|
||||||
new_model.Meta.table = sqlalchemy.Table(
|
new_model.Meta.table = sqlalchemy.Table(
|
||||||
@ -304,7 +308,7 @@ def choices_validator(cls: Type["Model"], values: Dict[str, Any]) -> Dict[str, A
|
|||||||
|
|
||||||
|
|
||||||
def populate_choices_validators( # noqa CCR001
|
def populate_choices_validators( # noqa CCR001
|
||||||
model: Type["Model"], attrs: Dict
|
model: Type["Model"], attrs: Dict
|
||||||
) -> None:
|
) -> None:
|
||||||
if model_initialized_and_has_model_fields(model):
|
if model_initialized_and_has_model_fields(model):
|
||||||
for _, field in model.Meta.model_fields.items():
|
for _, field in model.Meta.model_fields.items():
|
||||||
@ -317,7 +321,7 @@ def populate_choices_validators( # noqa CCR001
|
|||||||
|
|
||||||
class ModelMetaclass(pydantic.main.ModelMetaclass):
|
class ModelMetaclass(pydantic.main.ModelMetaclass):
|
||||||
def __new__( # type: ignore
|
def __new__( # type: ignore
|
||||||
mcs: "ModelMetaclass", name: str, bases: Any, attrs: dict
|
mcs: "ModelMetaclass", name: str, bases: Any, attrs: dict
|
||||||
) -> "ModelMetaclass":
|
) -> "ModelMetaclass":
|
||||||
attrs["Config"] = get_pydantic_base_orm_config()
|
attrs["Config"] = get_pydantic_base_orm_config()
|
||||||
attrs["__name__"] = name
|
attrs["__name__"] = name
|
||||||
|
|||||||
@ -45,12 +45,12 @@ class Model(NewBaseModel):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_row( # noqa CCR001
|
def from_row( # noqa CCR001
|
||||||
cls: Type[T],
|
cls: Type[T],
|
||||||
row: sqlalchemy.engine.ResultProxy,
|
row: sqlalchemy.engine.ResultProxy,
|
||||||
select_related: List = None,
|
select_related: List = None,
|
||||||
related_models: Any = None,
|
related_models: Any = None,
|
||||||
previous_table: str = None,
|
previous_table: str = None,
|
||||||
fields: List = None,
|
fields: List = None,
|
||||||
) -> Optional[T]:
|
) -> Optional[T]:
|
||||||
|
|
||||||
item: Dict[str, Any] = {}
|
item: Dict[str, Any] = {}
|
||||||
@ -60,9 +60,9 @@ class Model(NewBaseModel):
|
|||||||
related_models = group_related_list(select_related)
|
related_models = group_related_list(select_related)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
previous_table
|
previous_table
|
||||||
and previous_table in cls.Meta.model_fields
|
and previous_table in cls.Meta.model_fields
|
||||||
and issubclass(cls.Meta.model_fields[previous_table], ManyToManyField)
|
and issubclass(cls.Meta.model_fields[previous_table], ManyToManyField)
|
||||||
):
|
):
|
||||||
previous_table = cls.Meta.model_fields[
|
previous_table = cls.Meta.model_fields[
|
||||||
previous_table
|
previous_table
|
||||||
@ -90,12 +90,12 @@ class Model(NewBaseModel):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def populate_nested_models_from_row(
|
def populate_nested_models_from_row(
|
||||||
cls,
|
cls,
|
||||||
item: dict,
|
item: dict,
|
||||||
row: sqlalchemy.engine.ResultProxy,
|
row: sqlalchemy.engine.ResultProxy,
|
||||||
related_models: Any,
|
related_models: Any,
|
||||||
previous_table: sqlalchemy.Table,
|
previous_table: sqlalchemy.Table,
|
||||||
fields: List = None,
|
fields: List = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
for related in related_models:
|
for related in related_models:
|
||||||
if isinstance(related_models, dict) and related_models[related]:
|
if isinstance(related_models, dict) and related_models[related]:
|
||||||
@ -119,12 +119,12 @@ class Model(NewBaseModel):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def extract_prefixed_table_columns( # noqa CCR001
|
def extract_prefixed_table_columns( # noqa CCR001
|
||||||
cls,
|
cls,
|
||||||
item: dict,
|
item: dict,
|
||||||
row: sqlalchemy.engine.result.ResultProxy,
|
row: sqlalchemy.engine.result.ResultProxy,
|
||||||
table_prefix: str,
|
table_prefix: str,
|
||||||
fields: List = None,
|
fields: List = None,
|
||||||
nested: bool = False,
|
nested: bool = False,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
|
|
||||||
# databases does not keep aliases in Record for postgres, change to raw row
|
# databases does not keep aliases in Record for postgres, change to raw row
|
||||||
|
|||||||
@ -38,9 +38,7 @@ class Artist(ormar.Model):
|
|||||||
first_name = ormar.String(name="fname", max_length=100)
|
first_name = ormar.String(name="fname", max_length=100)
|
||||||
last_name = ormar.String(name="lname", max_length=100)
|
last_name = ormar.String(name="lname", max_length=100)
|
||||||
born_year = ormar.Integer(name="year")
|
born_year = ormar.Integer(name="year")
|
||||||
children = ormar.ManyToMany(
|
children = ormar.ManyToMany(Child, through=ArtistChildren)
|
||||||
Child, through=ArtistChildren
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class Album(ormar.Model):
|
class Album(ormar.Model):
|
||||||
|
|||||||
@ -53,9 +53,7 @@ class Item(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
categories = ormar.ManyToMany(
|
categories = ormar.ManyToMany(Category, through=ItemsXCategories)
|
||||||
Category, through=ItemsXCategories
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True, scope="module")
|
@pytest.fixture(autouse=True, scope="module")
|
||||||
|
|||||||
@ -239,8 +239,8 @@ async def test_fk_filter():
|
|||||||
|
|
||||||
tracks = (
|
tracks = (
|
||||||
await Track.objects.select_related("album")
|
await Track.objects.select_related("album")
|
||||||
.filter(album__name="Fantasies")
|
.filter(album__name="Fantasies")
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
assert len(tracks) == 3
|
assert len(tracks) == 3
|
||||||
for track in tracks:
|
for track in tracks:
|
||||||
@ -248,8 +248,8 @@ async def test_fk_filter():
|
|||||||
|
|
||||||
tracks = (
|
tracks = (
|
||||||
await Track.objects.select_related("album")
|
await Track.objects.select_related("album")
|
||||||
.filter(album__name__icontains="fan")
|
.filter(album__name__icontains="fan")
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
assert len(tracks) == 3
|
assert len(tracks) == 3
|
||||||
for track in tracks:
|
for track in tracks:
|
||||||
@ -294,8 +294,8 @@ async def test_multiple_fk():
|
|||||||
|
|
||||||
members = (
|
members = (
|
||||||
await Member.objects.select_related("team__org")
|
await Member.objects.select_related("team__org")
|
||||||
.filter(team__org__ident="ACME Ltd")
|
.filter(team__org__ident="ACME Ltd")
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
assert len(members) == 4
|
assert len(members) == 4
|
||||||
for member in members:
|
for member in members:
|
||||||
@ -327,8 +327,8 @@ async def test_pk_filter():
|
|||||||
|
|
||||||
tracks = (
|
tracks = (
|
||||||
await Track.objects.select_related("album")
|
await Track.objects.select_related("album")
|
||||||
.filter(position=2, album__name="Test")
|
.filter(position=2, album__name="Test")
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
assert len(tracks) == 1
|
assert len(tracks) == 1
|
||||||
|
|
||||||
|
|||||||
@ -49,10 +49,8 @@ class Post(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
title = ormar.String(max_length=200)
|
title = ormar.String(max_length=200)
|
||||||
categories = ormar.ManyToMany(
|
categories = ormar.ManyToMany(Category, through=PostCategory)
|
||||||
Category, through=PostCategory
|
author = ormar.ForeignKey(Author)
|
||||||
)
|
|
||||||
author= ormar.ForeignKey(Author)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
|
|||||||
@ -139,6 +139,7 @@ def test_sqlalchemy_table_is_created(example):
|
|||||||
@typing.no_type_check
|
@typing.no_type_check
|
||||||
def test_no_pk_in_model_definition(): # type: ignore
|
def test_no_pk_in_model_definition(): # type: ignore
|
||||||
with pytest.raises(ModelDefinitionError): # type: ignore
|
with pytest.raises(ModelDefinitionError): # type: ignore
|
||||||
|
|
||||||
class ExampleModel2(Model): # type: ignore
|
class ExampleModel2(Model): # type: ignore
|
||||||
class Meta:
|
class Meta:
|
||||||
tablename = "example2"
|
tablename = "example2"
|
||||||
@ -150,6 +151,7 @@ def test_no_pk_in_model_definition(): # type: ignore
|
|||||||
@typing.no_type_check
|
@typing.no_type_check
|
||||||
def test_two_pks_in_model_definition():
|
def test_two_pks_in_model_definition():
|
||||||
with pytest.raises(ModelDefinitionError):
|
with pytest.raises(ModelDefinitionError):
|
||||||
|
|
||||||
@typing.no_type_check
|
@typing.no_type_check
|
||||||
class ExampleModel2(Model):
|
class ExampleModel2(Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
@ -163,6 +165,7 @@ def test_two_pks_in_model_definition():
|
|||||||
@typing.no_type_check
|
@typing.no_type_check
|
||||||
def test_setting_pk_column_as_pydantic_only_in_model_definition():
|
def test_setting_pk_column_as_pydantic_only_in_model_definition():
|
||||||
with pytest.raises(ModelDefinitionError):
|
with pytest.raises(ModelDefinitionError):
|
||||||
|
|
||||||
class ExampleModel2(Model):
|
class ExampleModel2(Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
tablename = "example4"
|
tablename = "example4"
|
||||||
@ -174,6 +177,7 @@ def test_setting_pk_column_as_pydantic_only_in_model_definition():
|
|||||||
@typing.no_type_check
|
@typing.no_type_check
|
||||||
def test_decimal_error_in_model_definition():
|
def test_decimal_error_in_model_definition():
|
||||||
with pytest.raises(ModelDefinitionError):
|
with pytest.raises(ModelDefinitionError):
|
||||||
|
|
||||||
class ExampleModel2(Model):
|
class ExampleModel2(Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
tablename = "example5"
|
tablename = "example5"
|
||||||
@ -185,6 +189,7 @@ def test_decimal_error_in_model_definition():
|
|||||||
@typing.no_type_check
|
@typing.no_type_check
|
||||||
def test_string_error_in_model_definition():
|
def test_string_error_in_model_definition():
|
||||||
with pytest.raises(ModelDefinitionError):
|
with pytest.raises(ModelDefinitionError):
|
||||||
|
|
||||||
class ExampleModel2(Model):
|
class ExampleModel2(Model):
|
||||||
class Meta:
|
class Meta:
|
||||||
tablename = "example6"
|
tablename = "example6"
|
||||||
|
|||||||
@ -23,7 +23,7 @@ class JsonSample(ormar.Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
test_json= ormar.JSON(nullable=True)
|
test_json = ormar.JSON(nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class UUIDSample(ormar.Model):
|
class UUIDSample(ormar.Model):
|
||||||
@ -32,7 +32,7 @@ class UUIDSample(ormar.Model):
|
|||||||
metadata = metadata
|
metadata = metadata
|
||||||
database = database
|
database = database
|
||||||
|
|
||||||
id= ormar.UUID(primary_key=True, default=uuid.uuid4)
|
id = ormar.UUID(primary_key=True, default=uuid.uuid4)
|
||||||
test_text = ormar.Text()
|
test_text = ormar.Text()
|
||||||
|
|
||||||
|
|
||||||
@ -55,8 +55,8 @@ class Product(ormar.Model):
|
|||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
rating = ormar.Integer(minimum=1, maximum=5)
|
rating = ormar.Integer(minimum=1, maximum=5)
|
||||||
in_stock= ormar.Boolean(default=False)
|
in_stock = ormar.Boolean(default=False)
|
||||||
last_delivery= ormar.Date(default=datetime.now)
|
last_delivery = ormar.Date(default=datetime.now)
|
||||||
|
|
||||||
|
|
||||||
country_name_choices = ("Canada", "Algeria", "United States")
|
country_name_choices = ("Canada", "Algeria", "United States")
|
||||||
@ -71,10 +71,8 @@ class Country(ormar.Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(
|
name = ormar.String(max_length=9, choices=country_name_choices, default="Canada",)
|
||||||
max_length=9, choices=country_name_choices, default="Canada",
|
taxed = ormar.Boolean(choices=country_taxed_choices, default=True)
|
||||||
)
|
|
||||||
taxed= ormar.Boolean(choices=country_taxed_choices, default=True)
|
|
||||||
country_code = ormar.Integer(
|
country_code = ormar.Integer(
|
||||||
minimum=0, maximum=1000, choices=country_country_code_choices, default=1
|
minimum=0, maximum=1000, choices=country_country_code_choices, default=1
|
||||||
)
|
)
|
||||||
|
|||||||
@ -40,7 +40,7 @@ class Category(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
department= ormar.ForeignKey(Department, nullable=False)
|
department = ormar.ForeignKey(Department, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class Student(ormar.Model):
|
class Student(ormar.Model):
|
||||||
@ -51,8 +51,8 @@ class Student(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
schoolclass= ormar.ForeignKey(SchoolClass)
|
schoolclass = ormar.ForeignKey(SchoolClass)
|
||||||
category= ormar.ForeignKey(Category, nullable=True)
|
category = ormar.ForeignKey(Category, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class Teacher(ormar.Model):
|
class Teacher(ormar.Model):
|
||||||
@ -63,8 +63,8 @@ class Teacher(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
schoolclass= ormar.ForeignKey(SchoolClass)
|
schoolclass = ormar.ForeignKey(SchoolClass)
|
||||||
category= ormar.ForeignKey(Category, nullable=True)
|
category = ormar.ForeignKey(Category, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
|
|||||||
@ -29,7 +29,7 @@ class Track(ormar.Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
album= ormar.ForeignKey(Album)
|
album = ormar.ForeignKey(Album)
|
||||||
title = ormar.String(max_length=100)
|
title = ormar.String(max_length=100)
|
||||||
position = ormar.Integer()
|
position = ormar.Integer()
|
||||||
|
|
||||||
@ -41,7 +41,7 @@ class Cover(ormar.Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
album= ormar.ForeignKey(Album, related_name="cover_pictures")
|
album = ormar.ForeignKey(Album, related_name="cover_pictures")
|
||||||
title = ormar.String(max_length=100)
|
title = ormar.String(max_length=100)
|
||||||
|
|
||||||
|
|
||||||
@ -62,7 +62,7 @@ class Team(ormar.Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
org= ormar.ForeignKey(Organisation)
|
org = ormar.ForeignKey(Organisation)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
|
|
||||||
|
|
||||||
@ -73,7 +73,7 @@ class Member(ormar.Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
team= ormar.ForeignKey(Team)
|
team = ormar.ForeignKey(Team)
|
||||||
email = ormar.String(max_length=100)
|
email = ormar.String(max_length=100)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -36,7 +36,7 @@ class ToDo(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
text = ormar.String(max_length=500)
|
text = ormar.String(max_length=500)
|
||||||
completed= ormar.Boolean(default=False)
|
completed = ormar.Boolean(default=False)
|
||||||
|
|
||||||
|
|
||||||
class Category(ormar.Model):
|
class Category(ormar.Model):
|
||||||
@ -57,7 +57,7 @@ class Note(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
text = ormar.String(max_length=500)
|
text = ormar.String(max_length=500)
|
||||||
category= ormar.ForeignKey(Category)
|
category = ormar.ForeignKey(Category)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True, scope="module")
|
@pytest.fixture(autouse=True, scope="module")
|
||||||
|
|||||||
@ -30,7 +30,7 @@ class SchoolClass(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
department= ormar.ForeignKey(Department, nullable=False)
|
department = ormar.ForeignKey(Department, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class Category(ormar.Model):
|
class Category(ormar.Model):
|
||||||
@ -51,8 +51,8 @@ class Student(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
schoolclass= ormar.ForeignKey(SchoolClass)
|
schoolclass = ormar.ForeignKey(SchoolClass)
|
||||||
category= ormar.ForeignKey(Category, nullable=True)
|
category = ormar.ForeignKey(Category, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class Teacher(ormar.Model):
|
class Teacher(ormar.Model):
|
||||||
@ -63,8 +63,8 @@ class Teacher(ormar.Model):
|
|||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
schoolclass= ormar.ForeignKey(SchoolClass)
|
schoolclass = ormar.ForeignKey(SchoolClass)
|
||||||
category= ormar.ForeignKey(Category, nullable=True)
|
category = ormar.ForeignKey(Category, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
|
|||||||
@ -30,7 +30,7 @@ class Car(ormar.Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
id = ormar.Integer(primary_key=True)
|
id = ormar.Integer(primary_key=True)
|
||||||
manufacturer= ormar.ForeignKey(Company)
|
manufacturer = ormar.ForeignKey(Company)
|
||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
year = ormar.Integer(nullable=True)
|
year = ormar.Integer(nullable=True)
|
||||||
gearbox_type = ormar.String(max_length=20, nullable=True)
|
gearbox_type = ormar.String(max_length=20, nullable=True)
|
||||||
|
|||||||
@ -24,7 +24,7 @@ class Product(ormar.Model):
|
|||||||
name = ormar.String(max_length=100)
|
name = ormar.String(max_length=100)
|
||||||
company = ormar.String(max_length=200, server_default="Acme")
|
company = ormar.String(max_length=200, server_default="Acme")
|
||||||
sort_order = ormar.Integer(server_default=text("10"))
|
sort_order = ormar.Integer(server_default=text("10"))
|
||||||
created= ormar.DateTime(server_default=func.now())
|
created = ormar.DateTime(server_default=func.now())
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
|
|||||||
Reference in New Issue
Block a user