On Fri, Mar 28, 2014 at 1:16 AM,  <[email protected]> wrote:
> Hi,
>
> I'm trying to configure a table with autoload but can't quite get the syntax 
> to set up a self-relationship. This is my abbreviated) schema:
>
> CREATE TABLE sdssphoto.photoobj
> (
>   pk bigint NOT NULL DEFAULT nextval('photoobj_pk_seq'::regclass),
>   parent_photoobj_pk bigint
>  CONSTRAINT photoobj_pk PRIMARY KEY (pk),
>    CONSTRAINT parent_fk FOREIGN KEY (parent_photoobj_pk)
>       REFERENCES sdssphoto.photoobj (pk) MATCH SIMPLE
>       ON UPDATE NO ACTION ON DELETE NO ACTION,
> )
>
> and my code:
>
> class PhotoObj(Base):
>
>     __tablename__ = 'photoobj'
>     __table_args__ = {'autoload':True, 'schema':'sdssphoto'}
>
>     children = relationship('PhotoObj', backref=backref('parent', 
> remote_side=[PhotoObj.pk]))
>
> The error I get is "NameError: name 'PhotoObj' is not defined". I've tried 
> many iterations, but can't quite seem to get this right. Any suggestions 
> would be appreciated!
>

In Python, you can't refer to a class while it is being defined. In
this instance, you are using the bare name PhotoObj in the remote_side
parameter to your backref.

I *think* (but haven't tested) that you should be able to specify the
remote_side parameter as a string:

    children = relationship('PhotoObj', backref=backref('parent',
remote_side='[PhotoObj.pk]'))

The alternative is to define the "children" relationship after the
class has been defined:

class PhotoObj(Base):

    __tablename__ = 'photoobj'
    __table_args__ = {'autoload':True, 'schema':'sdssphoto'}

PhotoObj.children = relationship(PhotoObj, backref=backref('parent',
remote_side=[PhotoObj.pk]))

Hope that helps,

Simon

-- 
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to