Replies: 2 comments 11 replies
-
As a matter of fact you can but as of now it's kind of hacky as you need to overload your model As of now you can: from typing import Optional
import databases
import pytest
import sqlalchemy
from pydantic import EmailStr, HttpUrl, ValidationError
import ormar
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
class BaseMeta(ormar.ModelMeta):
metadata = metadata
database = database
class Test(ormar.Model):
class Meta(BaseMeta):
pass
def __init__(self, **kwargs):
# you need to pop non - db fields as ormar will complain that it's unknown field
email = kwargs.pop("email", self.__fields__['email'].get_default())
url = kwargs.pop("url", self.__fields__['url'].get_default())
super().__init__(**kwargs)
self.email = email
self.url = url
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=200)
email: Optional[EmailStr] # field optional - default to None
url: HttpUrl = "www.example.com" # field with default
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
@pytest.mark.asyncio
async def test_working_with_pydantic_fields():
async with database:
test = Test(name="Test", email="aka@go2.com")
assert test.name == "Test"
assert test.email == "aka@go2.com"
assert test.url == "www.example.com"
test.email = 'sdta@ada.pt'
assert test.email == "sdta@ada.pt"
await test.save()
test_check = await Test.objects.get()
assert test_check.name == "Test"
assert test_check.email is None
assert test_check.url == "www.example.com" Can you open another issue (in issues) to support native pydantic fields out of the box so I will remember that? |
Beta Was this translation helpful? Give feedback.
-
@collerek , thanks for this hacky trick:) Kindly advise , if by the same fashion for "forcing" field/key to support pyadntic, pseudo code from faker import Faker
class Test(ormar.Model):
class Meta(BaseMeta):
pass
def __init__(self, **kwargs):
fake = Faker()
self.first_name= fake.first_name()
self.last_name= fake.last_name()
id: int = ormar.Integer(primary_key=True)
first_name: str = ormar.String(max_length=10)
last_name: str = ormar.String(max_length=10)
|
Beta Was this translation helpful? Give feedback.
-
following documentation ormar supports 12 pydantic fields:
https://collerek.github.io/ormar/fields/field-types/
What is the consideration for not supporting all (or at least much more) fields which supported by pydantic ?
is there way adding pydatnic field manually to ormat model (not as non DB field).
In example - I need for PaymentCardNumber ,URL ,EmailStr and Json
Beta Was this translation helpful? Give feedback.
All reactions