Skip to content

Unable to use pydantic validators on Relation attributes #68

Open
@CisterMoke

Description

@CisterMoke

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from sqlmodel import Field, Relationship, SQLModel

class Address(SQLModel, table=True):
    id: Optional[int] = Field(primary_key=True)
    country: str
    city: str
    street: str
    street_number: int

class Building(SQLModel, table=True):
    id: int = Field(primary_key=True)
    address_id: int = Field(foreign_key=f"{ADDRESSES}.id")
    address: Address = Relationship()
    age: int

    class Config:
        arbitrary_types_allowed = True

    @validator('address', pre=True)
    def validate_address(cls, v):
        return Address.parse_obj(v)

# Importing Building produces the error "pydantic.errors.ConfigError: Validators defined with incorrect fields: validate_address (use check_fields=False if you're inheriting from the model and intended this)"

Description

I want to parse a Building instance from a nested dictionary d with the Building and Address class defined in the example code.

d = {
  'address': {
     'country': 'US',
     'city': 'New York',
     'street': 'Centre St',
     'street_num': 1},
   'age': 40
}

So far I have been unavailable to successfully execute Building.parse_obj(d). Commenting out the validator in Building solves the pydantic error bein raised but the address of the parsed building will be a dict instead of an Address instance

Operating System

Windows

Operating System Details

No response

SQLModel Version

0.0.4

Python Version

3.6.12

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions