Search code examples
pythonpyramid

Example of adding relationship to pyramid_blogr models


Working through the tutorial at http://pyramid-blogr.readthedocs.org/en/latest/ and would like to add a relationship between the user and entry models and then be able to have that FK field populated when a new post is added.

Here is what I have so far...

entry.py

...
class Entry(Base):
    __tablename__ = 'entries'
    id = Column(Integer, primary_key=True)
    title = Column(Unicode(255), unique=True, nullable=False)
    body = Column(UnicodeText, default=u'')
    created = Column(DateTime, default=datetime.datetime.utcnow)
    edited = Column(DateTime, default=datetime.datetime.utcnow)
    user_id = Column(Integer, ForeignKey('users.id'))

    user = relationship("User", backref=backref('entries'))
...

user.py

...
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(Unicode(255), unique=True, nullable=False)
    password = Column(Unicode(255), nullable=False)
    last_logged = Column(DateTime, default=datetime.datetime.utcnow)
    entries = relationship("Entry", order_by="entry.id", backref="user_id")

...

I'm assuming forms.py would also need a modification to pass the user_id as a hidden field but I may not be thinking about that correctly.


Solution

  • Brian,

    When you declare a relationship like "entries" (like you did in your snippets)

    and define a foreign key, you can do something like:

    user.entries.append(entry)
    

    And your foreign key will be auto populated and your newly created object will get added to session - you do NOT want to pass user_id as form parameter to your model - this would be unsafe operation as one user could save the entry for someone else.

    http://docs.sqlalchemy.org/en/rel_1_0/orm/basic_relationships.html?highlight=append#one-to-many

    Here is the section of sqlalchemy docs that illustrates it.