P
P
Pan Propan2021-11-19 21:29:32
Python
Pan Propan, 2021-11-19 21:29:32

Why doesn't alembic create migrations in sqlalchemy models?

There are three models with some connections between them.

Models
class Clinic(Base):
    '''Таблица клиники'''
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True, nullable=False, comment="Наименование")
    website = Column(String, comment="Веб-сайт")
    phone = Column(String(21), comment="Телефон")
    address = Column(String(500), comment="Адрес")
    logo = Column(String(200), comment="Логотип")
    start_time = Column(Time, comment="Начало рабочего дня")
    end_time = Column(Time, comment="Конец рабочего дня")
    rate_id = Column(Integer, ForeignKey("rate.id"))
    users = relationship("User", back_populates="clinic")
    rate = relationship("Rate", back_populates="clinics")


class Rate(Base):
    '''Таблица с тарифами'''
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50), unique=True, nullable=False, comment="Наименование")
    price = Column(Integer, nullable=False, comment="Стомость")
    is_active = Column(Boolean, default=True, comment="Активный")
    clinics = relationship("Clinic", back_populates="rate")


class User(Base):
    '''Модель пользователя'''
    id = Column(Integer, primary_key=True, index=True)
    first_name = Column(String, index=True)
    last_name = Column(String, index=True)
    patronymic = Column(String, index=True)
    birthday = Column(Date)
    image = Column(String, nullable=True)
    email = Column(String, unique=True, index=True, nullable=False)
    hashed_password = Column(String, nullable=False)
    is_active = Column(Boolean(), default=True)
    is_superuser = Column(Boolean(), default=False)
    clinic_id = Column(Integer, ForeignKey('clinic.id'))
    clinic = relationship("Clinic", back_populates="users")


When you try to create a migration, alembic swears.
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'clinic.rate_id' could not find table 'rate' with which to generate a foreign key to target column 'id'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pan Propan, 2021-11-20
@mgis

The solution was to replace
rate_id = Column(Integer, ForeignKey("rate.id"))

from app.models.rate import Rate #начала импортируем модель

rate_id = Column(Integer, ForeignKey(Rate.id))

I still don't understand why the string option didn't work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question