This is probably a rookie mistake, but while adding some test data to my database, I get this error in my terminal:
Traceback (most recent call last):
File "/python-sandbox/addpost.py", line 11, in
Post(
~~~~^
title = "First Post!",
^^^^^^^^^^^^^^^^^^^^^^
...<2 lines>...
tags = "First Tag"
^^^^^^^^^^^^^^^^^^
),
^
File "", line 4, in __init__
File "/python-sandbox/venv/lib/python3.13/site-packages/sqlalchemy/orm/state.py", line 571, in _initialize_instance
with util.safe_reraise():
~~~~~~~~~~~~~~~~~^^
File "/python-sandbox/venv/lib/python3.13/site-packages/sqlalchemy/util/langhelpers.py", line 224, in __exit__
raise exc_value.with_traceback(exc_tb)
File "/python-sandbox/venv/lib/python3.13/site-packages/sqlalchemy/orm/state.py", line 569, in _initialize_instance
manager.original_init(*mixed[1:], **kwargs)
~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
File "/python-sandbox/venv/lib/python3.13/site-packages/sqlalchemy/orm/decl_base.py", line 2182, in _declarative_constructor
setattr(self, k, kwargs[k])
~~~~~~~^^^^^^^^^^^^^^^^^^^^
File "/python-sandbox/venv/lib/python3.13/site-packages/sqlalchemy/orm/attributes.py", line 540, in __set__
self.impl.set(
~~~~~~~~~~~~~^
instance_state(instance), instance_dict(instance), value, None
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
)
^
File "/python-sandbox/venv/lib/python3.13/site-packages/sqlalchemy/orm/attributes.py", line 1951, in set
raise TypeError(
...<2 lines>...
)
TypeError: Incompatible collection type: str is not list-like
For context, I'll show my models.py file and the Python script that adds posts to the database.
# models.py
from datetime import datetime # Do I need this?
from sqlalchemy import Column, DateTime, ForeignKey, func, Integer, String, Table, Text
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from import Base
Base = declarative_base()
posts_tags = Table(
"posts_tags",
Base.metadata,
Column("post_id", Integer, ForeignKey("posts.id")),
Column("tag_id", Integer, ForeignKey("tags.id")),
)
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
title = Column(String(200), nullable=False)
body = Column(Text)
date = Column(DateTime(), server_default=func.now())
tags = relationship("Tag", secondary=posts_tags, back_populates="posts")
def __repr__(self):
return f""
class Tag(Base):
__tablename__ = 'tags'
id = Column(Integer, primary_key=True)
tag_name = Column(String(50), unique=True, nullable=False)
posts = relationship("Post", secondary=posts_tags, back_populates="tags")
def __repr__(self):
return f""
# addposts.py
from datetime import datetime # Do I need this?
from sqlalchemy import DateTime
from import SessionLocal
from models import Post, Tag
# Create a session
session = SessionLocal()
# Create posts
posts = [
Post(
title = "First Post!",
date = DateTime(),
body = "This is my first post!",
tags = {"First Tag"}
),
Post(
title = "Second Post, With More Text",
date = DateTime(),
body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
tags = {"Second Tag", "This Is A Long String Of Text For A Tag!"}
)
]
# Add posts to the session
session.add_all(posts)
# Commit the transaction
session.commit()
# Print the posts with their new IDs
for post in posts:
print(f"Added: {post} with ID: {post.post_id}")
# Close the session
session.close()
I'm not understanding why either the title or tags lines are not list-like (title shouldn't even be a list, so I don't know why that line's getting flagged to begin with), nor do I understand how to fix the error. Any ideas? Please note I'm using straight-up Python, not Flask or Django.