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

Python

David Hultén
David Hultén
7,115 Points

The 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)

3 Answers

Brian Jensen
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Brian Jensen
Treehouse Teacher

Yep, David Hultén, that is exactly what I wanted! ⭐

There are a couple of issues going on. The first is that, for some reason, your requirements.txt file includes a very large number of unnecessary packages:

aniso8601==10.0.1
argon2-cffi==21.3.0
asgiref==3.8.1
bcrypt==4.3.0
certifi==2025.6.15
charset-normalizer==3.4.2
click==8.1.8
contourpy==1.3.0
coverage==7.2.3
cycler==0.12.1
Deprecated==1.2.18
Django==3.2.19
django-bootstrap3==23.1
django-braces==1.15.0
django_debug_toolbar==3.8.1
djangorestframework==3.14.0
et_xmlfile==2.0.0
flake8==5.0.4
Flask==2.0.3
Flask-Bcrypt==1.0.1
Flask-HTTPAuth==4.7.0
Flask-Limiter==3.3.1
Flask-Login==0.6.2
Flask-RESTful==0.3.9
Flask-WTF==1.1.1
fonttools==4.58.4
greenlet==3.2.3
idna==3.10
importlib_resources==6.5.2
itsdangerous==2.0.1
Jinja2==3.1.6
kiwisolver==1.4.7
limits==4.2
markdown-it-py==3.0.0
markdown2==2.4.8
MarkupSafe==3.0.2
matplotlib==3.7.1
mccabe==0.7.0
mdurl==0.1.2
misaka==2.1.1
newrelic==8.8.0
numpy==1.24.3
openpyxl==3.1.2
ordered-set==4.1.0
packaging==24.2
pandas==1.5.3
peewee==3.16.2
pep8==1.7.1
Pillow==9.5.0
prettytable==3.6.0
pycodestyle==2.9.1
pycparser==2.21
pyflakes==2.5.0
Pygments==2.19.1
pyinotify==0.9.6
pyparsing==3.2.3
python-dateutil==2.9.0.post0
pytz==2025.2
requests==2.31.0
rich==13.9.4
six==1.17.0
SQLAlchemy==1.4.47
sqlparse==0.4.4
typing_extensions==4.14.0
urllib3==2.4.0
wcwidth==0.2.13
Werkzeug==2.0.3
wrapt==1.17.2
WTForms==3.2.1
zipp==3.23.0

One of these packages is SQLAlchemy v1.4.47, which explains your most recent error:

ImportError: cannot import name 'DeclarativeBase' from 'sqlalchemy.orm'

As we discussed earlier, that Class was introduced in SQLAlchemy v2.0.

You can follow these steps to resolve the issues and be able to run SQLAlchemy v2.0 with your updated model.py file:

1) In your workspace, delete the __pycache__ and env folders, as well as the requirements.txt and zoo.db files

2) Run the python3 -m venv env command in the Console to initialize a new environment.

3) Run the source ./env/bin/activate command in the Console to active the environment.

4) Run the pip install sqlalchemy command in the Console to install the most recent version of SQLAlchemy.

5) Run the pip freeze > requirements.txt command in the Console to generate a new requirements.txt file.

6) Right-click on the models.py file in the left sidebar, then click Refresh in the pop-up menu.

7) You should now see the recreated requirements.txt file, which should only contain these three packages now: greenlet==3.2.5, sqlalchemy==2.0.49, and typing-extensions==4.15.0

8) Run the python3 models.py command in the Console to generate the zoo.db file. This should now run without errors. Refresh the left sidebar again, and the successfully created zoo.db file should appear.

If you run into any snags with these steps, go ahead and create a new snapshot and share the link here. :thumbsup:

Brian Jensen
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Brian Jensen
Treehouse Teacher

Hiya David Hultén :wave:

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!

David Hultén
David Hultén
7,115 Points

i tried it the way you said it and i got this error: Traceback (most recent call last):
File "/home/treehouse/workspace/models.py", line 8, in <module>
from sqlalchemy.orm import sessionmaker, relationship, DeclarativeBase
ImportError: cannot import name 'DeclarativeBase' from 'sqlalchemy.orm' (/usr/local/lib/p ython3.9/site-packages/sqlalchemy/orm/init.py)

and here are the imports and what i changed:

from sqlalchemy import (create_engine, Column, Integer,
                        String, ForeignKey)
from sqlalchemy.orm import sessionmaker, relationship, DeclarativeBase


engine = create_engine("sqlite:///zoo.db", echo=False)
Session = sessionmaker(bind=engine)
session = Session()
class Base(DeclarativeBase):
    pass
Brian Jensen
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Brian Jensen
Treehouse Teacher

Hiya again David Hultén! :wave:

Hmm, based on that import snippet it appears that you now have them setup perfectly for SQLAlchemy 2.0+.

Can you please share a full copy of your project so that we can take a look your code as a whole, including your requirements.txt file:

If you are currently working on your project in the Treehouse Workspaces, you can checkout this video for sharing a snapshot of your workspace.

If you are currently working on your project locally, you can checkout this Git and GitHub Workflow for Developers workshop for sharing a repo of your project on GitHub.

Then we can better pinpoint the issue.