Hello group,

Suppose A has a ManyToOne relation to B (A is a child of B). I want to perform 
something like : 
a.b_id = b.id
assert a.b == b

How do I do this in sqlalchemy ? 

The following attempt failed 

-------


from sqlalchemy                 import *
from sqlalchemy.orm             import *
from sqlalchemy.ext.declarative import declarative_base

session            = sessionmaker()()
Base               = declarative_base()
metadata           = Base.metadata
metadata.bind      = "postgres://somedb"

class SQLModel:
    reprattr = "name"
    def __repr__(self):
        """
        Will a return string of the form <SomeModel fieldn="filedn value"...  
id = 1>
        """
        if type(self.reprattr) != list :
            self.reprattr = [self.reprattr]
        attrstr =  " ".join(["%s=\"%s\"" % (attr, getattr(self,attr))
                             for attr in self.reprattr 
                             if hasattr(self,attr)
                             ]
                            )
        reprstr = "<%s id=%s at 0x%x %s >" % (self.__class__.__name__, 
self.id,id(self),attrstr)
        return reprstr
    
class Country (Base, SQLModel):
    """Creates a Country Object."""
    __tablename__ = "countries"
    id            = Column(Integer, primary_key=True)
    name          = Column(String, nullable=False)


class City (Base, SQLModel):
    """Creates a City Object."""
    __tablename__ = "cities"
    id         = Column(Integer, primary_key=True)
    country_id = Column(Integer, ForeignKey("countries.id", 
ondelete="RESTRICT"))
    name       = Column(String, nullable=False)
    country    = relation(Country, backref="cities")

metadata.drop_all()
metadata.create_all()

algiers = City(name="Algiers")
algeria = Country(name="Algeria")
session.add_all([algiers,algeria])
session.flush()
algiers.country_id = algeria
session.flush()
print algiers.country
# >>> None


Any help appreciated. 

Y.Chaouche


      

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to