AttributeError thrown by relationship during unit testing

32 views
Skip to first unread message

Sam Raker

unread,
Jan 11, 2016, 3:47:59 PM1/11/16
to sqlalchemy
Using SQLAlchemy 1.0.9's declarative extension, I've got a many-to-one relationship defined thusly:

class Article(Base):
   
...
   publisher_id
= schema.Column(sqltypes.Integer, schema.ForeignKey('publishers.id'))
...
class Publisher(Base):
   __tablename__
= 'publishers'
   
...
   articles
= relationship('Article', backref='publisher')


I've got some code I'd like to test that looks like this:

articles = session.query(Article).filter(...).join(Article.publisher).filter(Publisher.name ==...)...

The code works fine, but while trying to test it with python 2.7's unittest module, I keep getting 
AttributeError: type object 'Article' has no attribute 'publisher'

How do I resolve this? I'm importing both Article and Publisher into my test file. I _really_ don't want to have to connect to a local db just to get instrumented attributes to work properly, and I don't want to have to refactor my code to use Article.publisher_id--as it'd involve either hard-coding (brittle) or two separate ORM/SQL calls (obnoxious)--just to make tests work.

Michael Bayer

unread,
Jan 12, 2016, 9:23:24 AM1/12/16
to sqlal...@googlegroups.com


Sent from my iPhone
--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Michael Bayer

unread,
Jan 12, 2016, 9:25:13 AM1/12/16
to sqlal...@googlegroups.com


Two options -  either use back_populates format (search the docs) to set up bidirectional relationships, or call configure_mappers() after the model classes have been defined.

On Jan 11, 2016, at 3:47 PM, Sam Raker <sra...@elitedaily.com> wrote:

Sam Raker

unread,
Jan 12, 2016, 9:38:28 AM1/12/16
to sqlal...@googlegroups.com
I just ended up taking advantage of the fact that you can pass attribute names as strings to join, but thanks for the tips!

--
You received this message because you are subscribed to a topic in the Google Groups "sqlalchemy" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/sqlalchemy/mrqsB-YyCsw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to sqlalchemy+...@googlegroups.com.

To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.



--

Sam Raker
Application Developer

sra...@elitedaily.com

30 W 24th St., 12th Floor
New York, NY 10010

Download the Elite Daily iOS App

Reply all
Reply to author
Forward
0 new messages