Hopefully I used the right verbiage in the question to describe the problem, but I will detail it more extensively below.
I am writing a SQL Alchemy database package that I want to then extend across different database projects. The example below would be I define the database package to have a User and Post with primitive values and then I import and extend it in another package with more features.
Although the database sets up the extended models and I am able to populate it correctly. Querying the features results in the models pointing at the original package instead of the new one. Semi-working, excerpt example below:
The following is the database package with the primitive models. Let’s say the file is models.py
.
from sqlalchemy import Column, Integer, String, ForeignKey, Table
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "author"
id = Column(Integer, primary_key=True)
first_name = Column(String)
last_name = Column(String)
posts = relationship("model.Post", backref=backref("author"), enable_typechecks=False)
class Post(Base):
__tablename__ = "book"
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey("author.author_id"))
user = relationship("model_example.User", backref=backref("book"))
title = Column(String)
These models would be extended in this new project, lets say the file is project1_models.py
from models import Base, User, Post
from sqlalchemy import Column, String
class User(User, Base):
address = Column(String)
class Post(Post, Base):
content = Column(String)
So although when I populate the database of the with project1_models.py models, the database features the correct columns, when I query Post.content
or User.address
I get a traceback error that the object doesn’t have that attribute and the type is models.Post
instead of project1_models.Post
I am thinking this problem is happening because in the models.py
I explicitly set the relationship to model.Post
so SQL Alchemy is tying that relationship to models.Post instead of project1_models.Post.
My project is a little more complex than the example, so I want to avoid having to redefine the relationships every time I start a project while using my database package.