0

I have two classes:

class Foo(SQLModel):
  id: str
  x: str
  y: str

class Bar(SQLModel):
  id: str
  foo_id: str
  z: str

I create a Foreign Key with Alembic migrations like this:

def upgrade():
    bar_table = op.create_table(
        "bars",
        sa.Column("id", sa.String, nullable=False),
        sa.Column("foo_id", sa.String, nullable=False),
        sa.Column("foo_id", sa.String, nullable=False),
        sa.PrimaryKeyConstraint("id"),
        sa.ForeignKeyConstraint(
            ["foo_id"],
            ["foos.id"],
        ),
    )

I'd like to access Foo values inside Bar class methods, e.g.:

class Bar(SQLModel):
      id: str
      foo_id: str
      z: str

  def process(self):
        # access Foo values, e.g. `self.z = Foo.x`´

Is this possible, or should I make z to have a FK reference to Foo.x?

lr_optim
  • 299
  • 1
  • 10
  • 30
  • 1
    Usually you'd compose `class Bar` with a `foo: Foo` in the pydantic model, and then use `foo = relationship('FooORMModel', ..)` in your SQLAlchemy model; that way you'll automagically get the Bar instance mapped into your `foo` object when returning it. When it gets submitted (to create the object), you'll usually want to resolve and validate `foo_id` anyway, insert the row - and then you can return the inserted row with everything populated from SQLAlchemy's ORM. If you're doing this manually, it'll be your responsibility to create the Foo reference when creating your `Bar` object – MatsLindh May 18 '22 at 08:02
  • 1
    Maybe the `fastapi` and `pydantic` tags are not necessary in this question. It looks like you are asking about `alembic`. – Hernán Alarcón May 22 '22 at 00:40

0 Answers0