Home > Blockchain >  Creating relationship between models when in separate files FLASK, SQLalchemy
Creating relationship between models when in separate files FLASK, SQLalchemy

Time:12-23

How can I properly establish a foreign key relationship between these two models when they are currently in separate folders?

from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
from testserver.database import Base
from datetime import datetime


class Service(Base):
    __tablename__ = 'services'

    id = Column(Integer(), primary_key=True)
    name = Column(String(25), nullable=False, unique=True)
    description = Column(String(80), nullable=False)
    date_created = Column(DateTime(), default=datetime.utcnow)
    provider_id = Column(String, ForeignKey('provider.id'))
from sqlalchemy import Column, String, Integer, DateTime
from sqlalchemy.orm import relationship
from testserver.database import Base
from datetime import datetime
from testserver.database import db_session


class Provider(Base):
    __tablename__ = 'providers'

    id = Column(Integer(), primary_key=True)
    name = Column(String(25), nullable=False, unique=True)
    description = Column(String(80), nullable=False)
    date_created = Column(DateTime(), default=datetime.utcnow)
    services = relationship(
        'Service', cascade='all, delete-orphan', backref='provided_by')

from sqlalchemy.ext.declarative import declared_attr


class Base(object):
    __abstract__ = True

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

the code above currently throws an err:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'services.provider_id' could not find table 'provider' with which to generate a foreign key to target column 'id'

any recommendations or solutions would be greatly apprecieted

CodePudding user response:

I assume that you have a typo here:

provider_id = Column(String, ForeignKey('provider.id'))

In relationship you provided lowercased model name, instead of table name. If you replace provider with providers (because it is a name of your table) it should fix your problem

provider_id = Column(String, ForeignKey('providers.id'))
  • Related