add enum field (#626)

* add enum field

* add decorator for asyncio

* fix enum typing, additional tests, add docs

* add more tests

Co-authored-by: collerek <collerek@gmail.com>
This commit is contained in:
Ethon
2022-04-27 18:01:00 +08:00
committed by GitHub
parent 2caa17812a
commit ebf7c6e06f
10 changed files with 193 additions and 17 deletions

View File

@ -200,8 +200,23 @@ When loaded it's always python UUID so you can compare it and compare two format
### Enum
Although there is no dedicated field type for Enums in `ormar` you can change any
field into `Enum` like field by passing a `choices` list that is accepted by all Field types.
There are two ways to use enums in ormar -> one is a dedicated `Enum` field that uses `sqlalchemy.Enum` column type, while the other is setting `choices` on any field in ormar.
The Enum field uses the database dialect specific Enum column type if it's available, but fallback to varchar if this field type is not available.
The `choices` option always respect the database field type selected.
So which one to use depends on the backend you use and on the column/ data type you want in your Enum field.
#### Enum - Field
`Enum(enum_class=Type[Enum])` has a required `enum_class` parameter.
* Sqlalchemy column: `sqlalchemy.Enum`
* Type (used for pydantic): `Type[Enum]`
#### Choices
You can change any field into `Enum` like field by passing a `choices` list that is accepted by all Field types.
It will add both: validation in `pydantic` model and will display available options in schema,
therefore it will be available in docs of `fastapi`.
@ -210,7 +225,7 @@ If you still want to use `Enum` in your application you can do this by passing a
and later pass value of given option to a given field (note tha Enum is not JsonSerializable).
```python
# not that imports and endpoints declaration
# note that imports and endpoints declaration
# is skipped here for brevity
from enum import Enum
class TestEnum(Enum):
@ -244,4 +259,4 @@ response = client.post(
[relations]: ../relations/index.md
[queries]: ../queries.md
[pydantic]: https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation
[server default]: https://docs.sqlalchemy.org/en/13/core/defaults.html#server-invoked-ddl-explicit-default-expressions
[server default]: https://docs.sqlalchemy.org/en/13/core/defaults.html#server-invoked-ddl-explicit-default-expressions

View File

@ -646,10 +646,11 @@ Available Model Fields (with required args - optional ones in docs):
* `Decimal(scale, precision)`
* `UUID()`
* `LargeBinary(max_length)`
* `EnumField` - by passing `choices` to any other Field type
* `Enum(enum_class)`
* `Enum` like Field - by passing `choices` to any other Field type
* `EncryptedString` - by passing `encrypt_secret` and `encrypt_backend`
* `ForeignKey(to)`
* `ManyToMany(to, through)`
* `ManyToMany(to)`
### Available fields options
The following keyword arguments are supported on all field types.