I am defining a model for companies using SQLModel the code thus far is as follows:
from typing import Optional
from sqlmodel import SQLModel, Field, JSON
from sqlalchemy import Column
from pydantic import validator
class Company(SQLModel, table=True):
name:str = Field(index=True, unique=True)
email:str
phone:int
postal_address:dict = Field(default={}, sa_column=Column(JSON))
shipping_address:Optonal[dict] = Field(default=None, sa_column=Column(JSON))
@validator('address')
def validate_address(cls, v):
fields = ["street_address", "city", "state", "country", "postal_code"]
for k in v:
if k not in fields:
raise ValueError("Please ensure that the address provided has all the necessary fields.")
return v
What i want to do is define a class Address like this :
class Address(SQLModel or Something Else):
street_address:str
city:str
state:str
country:str
postal_code:int
and use this Address class as a field type in my company model like this:
class Company(SQLModel, Table=True):
# Other Fields
postal_address:Address
shpping_address:Optional[Address]
what want to achieve basically is to define a schema for the address field without adding another address table in the database and defining relationships for the company and address tables for the postal and shipping address.
When i inherit from SQLModel in my Address class i get an error saying that there is no matching field type in sqlalchemy.
so far only solution I can think of is using dict as field type and validating it using a validator as mentioned above but I have to use validator to check if the data provided conforms to the schema I want for the address field, can this be achieved in a better way, thanks.
I also can define a request model for address and company separately like this
class AddressRequest(SQLModel):
street_address:str
city:str
state:str
country:str
postal_code:int
class CompanyRequest(SQLModel):
name:str = Field(index=True, unique=True)
email:str
phone:int
postal_address:AddressRequest
shipping_address:AddressRequest
gst_no:str
fy_start:date
fy_end:date
but i get the 422 error in fastapi.