1

Newish to SQLAlchemy (so my terminology may be a bit off). I want to create a database object inside the constructor of another, but the problem is I can't add said object to the session, so I get an error.

My schema looks a bit like the following:

class Tag(Base):
    __tablename__ = 'tag'

    id = Column(Integer, Sequence('tag_id_seq'), primary_key=True, nullable=False)
    type = Column(String(1), nullable=False)
    name = Column(String(255), unique=True, nullable=False)

    def __init__(self, type, name):
        self.type=type
        self.name=name

    def __repr__(self):
        return "<Tag('%s')>" % (self.id)


class Venue:
    __tablename__ = 'venue'

    tag_id = Column(Integer)
    tag_type = Column(String(1), nullable=False)
    location = Column(String(255), nullable=False)

    tag = ForeignKeyConstraint(
            (tag_id, tag_type),
            (Tag.id, Tag.type),
            onupdate='RESTRICT',
            ondelete='RESTRICT',
            )

    def __init__(self,name,location):
        self.tag = Tag('V',name)
        self.location = location

When I do the following:

session.add(Venue("Santa's Cafe","South Pole"))

I get an error:

UnmappedInstanceError: Class '__builtin__.instance' is not mapped

I assume this is because the the Tag object created in Venue's constructor is not added to the session. My question is how/when do I do this. (I'd really prefer to create that Tag object in the constructor if possible). I think I could do this with a scoped_session but that seems like a really bad solution.

Thanks

2
  • 3
    Shouldn't Venue inherit from Base? Commented Nov 27, 2011 at 3:24
  • Yes. (amongst other problems!) Commented Nov 29, 2011 at 12:03

1 Answer 1

2
  1. Inherit Venue from Base. Otherwise Venue won't be mapped.
  2. Move ForeignKeyConstraint to __table_args__.
  3. Replace currently meaningless tag property with relationship to Tag. The default value of cascade parameter to relationship contains 'save-update' rule that will add new referred object to the same session as parent.

From documentation:

save-update - cascade the Session.add() operation. This cascade applies both to future and past calls to add(), meaning new items added to a collection or scalar relationship get placed into the same session as that of the parent, and also applies to items which have been removed from this relationship but are still part of unflushed history.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, good explanation there. Stll getting used to the way sqlalchemy tells me what is wrong.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.