Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
David Hultén
6,709 PointsThe console is saying that there is an incompatibility with SQLAlchemy2.0 and I don't how to fix it
here is my code and when i run it in the console it says that the argument declarative_base() is incompatible with SQLAlchemy2.0
# Animals
# ID | Name | Habitat
# Zookeeper Log
# ID | Animal ID (Foreign Key) | Notes
from sqlalchemy import (create_engine, Column, Integer,
String, ForeignKey)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
engine = create_engine("sqlite:///zoo.db", echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Animal(Base):
__tablename__ = "animals"
id = Column(Integer, primary_key=True)
name = Column(String)
habitat = Column(String)
logs = relationship("Logbook", back_populates="animal")
def __repr__(self):
return f"""
\nAnimal {self.id}\r
Name = {self.name}\r
Habitat = {self.habitat}
"""
class Logbook(Base):
__tablename__ = "logbook"
id = Column(Integer, primary_key=True)
animal_id = Column(Integer, ForeignKey("animals.id"))
notes = Column(String)
animal = relationship("Animal", back_populates= "logs")
def __repr__(self):
return f"""
\nLogbook {self.id}\r
Animal ID = {self.animal_id}\r
Notes = {self.notes}
"""
if __name__ == "__main__":
Base.metadata.create_all(engine)
1 Answer
Brian Jensen
Treehouse TeacherHiya David Hultén
Ah, yeah in 2.0 the declarative_base() function was converted to a Class and moved to the orm instead. There are just a couple small changes you need to make to your code for it to work with 2.0+.
1) Delete line 8 completely:
from sqlalchemy.ext.declarative import declarative_base
2) Then, change line 9 to include the DeclarativeBase Class as part of the imports:
from sqlalchemy.orm import sessionmaker, relationship, DeclarativeBase
3) Lastly, change line 15 from a function:
Base = declarative_base()
Into a Class:
class Base(DeclarativeBase):
pass
After that, your code should run correctly, and the zoo.db file should be successfully created.
Another option, if you’d like to follow along more closely with the course code, is to install the same version of SQLAlchemy being used: pip install sqlalchemy==1.4.22.
Let us know if you run into any issues!