'How can I create a backref relationship from sqlalchemy in a pydantic model?

I want to have a set of categories. This categories can have a parent category. Example: Music -> Guitars.

I have this sql alchemy table:

class Category(Base):
    """
    Model of a category
    """
    __tablename__ = "category"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True, nullable=False)
    color = Column(String, index=True, nullable=True) # Expected to be an HEX string
    description = Column(String, index=True, nullable=True)
    parent_id = Column(Integer, ForeignKey("category.id"), nullable=True)

    parent = relationship("Category", foreign_keys=[parent_id])

So I created the following classes:

from typing import Optional
from pydantic import BaseModel


class CategoryBase(BaseModel):
    name: str
    color: str | None = None
    description: str | None = None
    parent_id: int | None = None

class CategoryCreate(CategoryBase):
    pass

class Category(CategoryBase):
    id: int
    parent: Optional[Category] # <--- I want to do something like this

    class Config:
        orm_mode = True

How can I make pydantic return the Category as for example:

[
  {
    "name": "Guitar",
    "color": "string",
    "parent_id": 0,
    "id": 1,
    "description": "string",
    "parent": {
        "name": "Music",
        "color": "string",
        "parent_id": null,
        "parent": null,
        "id": 0,
        "description": "string"
      }
  },
  {
        "name": "Music",
        "color": "string",
        "parent_id": null,
        "parent", null,
        "id": 0,
        "description": "string"
      }
 ]

Is there a way of defining that optional "self class" in pydantic?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source