[sqlalchemy] Problem with a query
Hi all, It doesn't do the second filter with those queries: session.query(User).options(joinedload("channels")).filter(User.id == int(userId)).filter(Channel.title != "zeptextstuff.txt").order_by(Channel.titleView).first() or session.query(User).join(User.channels).filter(User.id == int(userId)).filter(Channel.title != "zeptextstuff.txt").order_by(Channel.titleView).first() or session.query(User).options(joinedload("channels")).filter(and_(User.id == int(userId), Channel.title != "zeptextstuff.txt")).order_by(Channel.titleView).first() I get a user with a list of sorted channels, but I also get "zeptextstuff.txt" channel. Any clue?? Thanks in advance! -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@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.
[sqlalchemy] How can I differentiate between relationship?
Hi all, I have this table: class Comparation(Base): """Represents comparation between two post""" __tablename__ = "comparations" _id = Column("id", Integer, primary_key=True) _number = Column("number", Integer) _total = Column("total", Integer) _average = Column("average", Float) _postAId = Column("postA_id", Integer, ForeignKey("posts.id")) _postBId = Column("postB_id", Integer, ForeignKey("posts.id")) _postA = relationship("Post", uselist=False) _postB = relationship("Post", uselist=False) It has two ForeignKeys pointing the same table, but it also has two relationships related to those ForeignKeys. How can I relate _postAId to _postA? Thanks in advance! -- 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.
[sqlalchemy] Re: Problem with one relation
Yes, that's what I want. I already have the two relations that I want.: One is in Playlist, items = relationship("PlaylistItem", cascade="all, delete", backref="playlists"). If I understand properly, this allows Playlist to contain "PlaylistItems" And the another one is in PlaylistItem, playlist = relationship("Playlist", uselist=False). This one is the one that allows the PlaylistItem to contain objects of "Playlist" type. (Or at least, that's what I'd like it to be). This shouldn't be pointing to its Playlist parent, but to a different Playlist (which this item contains, because a Playlist can contain other Playlists inside) I guess for that I'd need another ForeignKey("playlists.id"), but I don't really know how to differentiate this ForeignKey from the one that is pointing to its "parent" Playlist object (or record). Thank you for your help, btw On Dec 7, 10:16 am, Michael Bayer wrote: > On Dec 7, 2010, at 10:09 AM, Alvaro Reinoso wrote: > > > The relation is OK, one-to-many between Playlist and PlaylisItem. > > However, PlaylistItem can contain one Playlist or one Layout and that > > Playlist could be in many PlaylistItems. I know it's weird relation if > > I already have Playlist as parent of PlaylistItem, but could I get > > this? > > If you mean, you want PlaylistItem.playlist to be independent of > Playlist.items, just use two different foreign keys and two different > relationships. Otherwise I don't really have enough detail here to know > what you're asking for. > > > > > Thanks! > > > On Dec 6, 3:51 pm, Michael Bayer wrote: > >> On Dec 6, 2010, at 2:39 PM, Alvaro Reinoso wrote: > > >>> Hi all, > > >>> I have those two classes: > > >>> class Playlist(rdb.Model): > >>> """Represents playlist. It may contain playlist items""" > >>> rdb.metadata(metadata) > >>> rdb.tablename("playlists") > > >>> id = Column("id", Integer, primary_key=True) > >>> title = Column("title", String(50)) > >>> pending = Column("pending", Boolean) > > >>> items = relationship("PlaylistItem", cascade="all, delete", > >>> backref="playlists") > >>> screens = relationship("Screen", secondary=playlist_screens, > >>> backref="playlists") > > >>> class PlaylistItem(rdb.Model): > >>> """Represents a playlist of items in Schedule page""" > >>> rdb.metadata(metadata) > >>> rdb.tablename("playlist_items") > > >>> id = Column("id", Integer, primary_key=True) > >>> title = Column("title", String(50)) > >>> runtime = Column("runtime", Integer) > >>> layoutId = Column("layout_id", Integer, ForeignKey("layouts.id")) > >>> playlistId = Column("playlist_id", Integer, > >>> ForeignKey("playlists.id")) > > >>> layout = relationship("Layout", uselist=False) > >>> playlist = relationship("Playlist", uselist=False) > > >>> One playlist can contain many PlaylistItem and PlaylistItem could > >>> contain layout or another playlist. The problem is when adding a > >>> PlaylistItem to a Playlist, PlaylistItem automatically gets the id of > >>> its parent (playlist_id). How can I avoid this? > > >>> Thanks in advance! > > >> the "items" collection of Playlist represents a one-to-many reference to a > >> list of PlaylistItems. A PlaylistItem in turn can only be referenced by > >> one parent. The items/playlists relationships therefore manage the > >> "playlistId" attribute to be the one foreign key represented by this > >> ownership. If a PlaylistItem is capable of having multiple Playlist > >> parents, this relationship should be changed to a many-to-many. > >> Reference on relationship() patterns is > >> athttp://www.sqlalchemy.org/docs/orm/relationships.html#basic-relationa > > >>> -- > >>> 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 > >>> athttp://groups.google.com/group/sqlalchemy?hl=en. > > > -- > > 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 > > athttp://groups.google.com/group/sqlalchemy?hl=en. -- 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.
[sqlalchemy] Re: Problem with one relation
The relation is OK, one-to-many between Playlist and PlaylisItem. However, PlaylistItem can contain one Playlist or one Layout and that Playlist could be in many PlaylistItems. I know it's weird relation if I already have Playlist as parent of PlaylistItem, but could I get this? Thanks! On Dec 6, 3:51 pm, Michael Bayer wrote: > On Dec 6, 2010, at 2:39 PM, Alvaro Reinoso wrote: > > > > > Hi all, > > > I have those two classes: > > > class Playlist(rdb.Model): > > """Represents playlist. It may contain playlist items""" > > rdb.metadata(metadata) > > rdb.tablename("playlists") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(50)) > > pending = Column("pending", Boolean) > > > items = relationship("PlaylistItem", cascade="all, delete", > > backref="playlists") > > screens = relationship("Screen", secondary=playlist_screens, > > backref="playlists") > > > class PlaylistItem(rdb.Model): > > """Represents a playlist of items in Schedule page""" > > rdb.metadata(metadata) > > rdb.tablename("playlist_items") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(50)) > > runtime = Column("runtime", Integer) > > layoutId = Column("layout_id", Integer, ForeignKey("layouts.id")) > > playlistId = Column("playlist_id", Integer, > > ForeignKey("playlists.id")) > > > layout = relationship("Layout", uselist=False) > > playlist = relationship("Playlist", uselist=False) > > > One playlist can contain many PlaylistItem and PlaylistItem could > > contain layout or another playlist. The problem is when adding a > > PlaylistItem to a Playlist, PlaylistItem automatically gets the id of > > its parent (playlist_id). How can I avoid this? > > > Thanks in advance! > > the "items" collection of Playlist represents a one-to-many reference to a > list of PlaylistItems. A PlaylistItem in turn can only be referenced by one > parent. The items/playlists relationships therefore manage the "playlistId" > attribute to be the one foreign key represented by this ownership. If a > PlaylistItem is capable of having multiple Playlist parents, this > relationship should be changed to a many-to-many. Reference on > relationship() patterns is > athttp://www.sqlalchemy.org/docs/orm/relationships.html#basic-relationa > > > > > -- > > 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 > > athttp://groups.google.com/group/sqlalchemy?hl=en. -- 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.
[sqlalchemy] Problem with one relation
Hi all, I have those two classes: class Playlist(rdb.Model): """Represents playlist. It may contain playlist items""" rdb.metadata(metadata) rdb.tablename("playlists") id = Column("id", Integer, primary_key=True) title = Column("title", String(50)) pending = Column("pending", Boolean) items = relationship("PlaylistItem", cascade="all, delete", backref="playlists") screens = relationship("Screen", secondary=playlist_screens, backref="playlists") class PlaylistItem(rdb.Model): """Represents a playlist of items in Schedule page""" rdb.metadata(metadata) rdb.tablename("playlist_items") id = Column("id", Integer, primary_key=True) title = Column("title", String(50)) runtime = Column("runtime", Integer) layoutId = Column("layout_id", Integer, ForeignKey("layouts.id")) playlistId = Column("playlist_id", Integer, ForeignKey("playlists.id")) layout = relationship("Layout", uselist=False) playlist = relationship("Playlist", uselist=False) One playlist can contain many PlaylistItem and PlaylistItem could contain layout or another playlist. The problem is when adding a PlaylistItem to a Playlist, PlaylistItem automatically gets the id of its parent (playlist_id). How can I avoid this? Thanks in advance! -- 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.
[sqlalchemy] Re: Weird behavior
I just fixed the error. I didn't see it before. I initialize the userGroup attribute to new UseGroup instance in one of the migration functions. Thanks! On Dec 2, 11:22 am, Michael Bayer wrote: > On Dec 2, 2010, at 11:13 AM, Alvaro Reinoso wrote: > > > > > I think I see the error. Those are the whole tables: > > > class User(rdb.Model): > > """Represents the user""" > > rdb.metadata(metadata) > > rdb.tablename("users") > > > id = Column("id", Integer, primary_key=True) > > name = Column("name", String(50)) > > email = Column("email", String(50)) > > password = Column("password", String(50)) > > hashed = Column("hashed", Boolean) > > military = Column("military", Boolean) > > agreedLicense = Column("agreed_license", Boolean) > > userGroupId = Column("user_group_id", Integer, > > ForeignKey("user_groups.id")) > > > userGroup = relationship("UserGroup", uselist=False) > > channels = relationship("Channel", secondary=user_channels, > > order_by="Channel.titleView", backref="users") > > mediaGroups = relationship("MediaGroup", secondary=user_media_groups, > > order_by="MediaGroup.title", backref="users") > > screens = relationship("Screen", secondary=user_screens, > > backref="users") > > screenGroups = relationship("ScreenGroup", > > secondary=user_screen_groups, order_by="ScreenGroup.title", > > backref="users") > > > class UserGroup(rdb.Model): > > """Represents a group of users with the same features""" > > rdb.metadata(metadata) > > rdb.tablename("user_groups") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(50)) > > > users = relationship("User", order_by="User.name", cascade="all, > > delete", backref="user_groups") > > permissions = relationship("Permission", > > secondary=user_group_permissions, backref="user_groups") > > > I have pretty similar tables and relations, but the different with > > other tables is I have this relation: userGroupId = > > Column("user_group_id", Integer, ForeignKey("user_groups.id")). So it > > seems every time when a user is created, it creates a new row in the > > user_groups and that row is related to that user. I think it's because > > of that relation. > > > How could I avoid this? > > there's really not enough detail here to see, but the only way associating > two existing objects together creates a row is if "secondary" is used, here > if "user_groups" is mapped as a secondary somewhere, which I do not see. if > you've mapped to a table explicitly, you should not use that table as the > "secondary" argument elsewhere, or the relationship with "secondary" should > be set up as viewonly=True. > > > > > Thanks! > > > On Dec 1, 6:35 pm, Michael Bayer wrote: > >> On Dec 1, 2010, at 5:46 PM, Alvaro Reinoso wrote: > > >>> Hello, > > >>> I have a system to manage users in my application, but I'm getting > >>> some troubles with it. > > >>> Every user has to belong to a group of users. One user can only be in > >>> one group. > > >>> I have those tables (inheriting from rdb.Model is basically the same > >>> thing than using sqlalchemy's declarative model) > > >>> class User(rdb.Model): > >>> """Represents the user""" > >>> rdb.metadata(metadata) > >>> rdb.tablename("users") > > >>> id = Column("id", Integer, primary_key=True) > >>> name = Column("name", String(50)) > >>> > > >>> userGroup = relationship("UserGroup", uselist=False) > >>> . > > >>> class UserGroup(rdb.Model): > >>> """Represents a group of users with the same features""" > >>> rdb.metadata(metadata) > >>> rdb.tablename("user_groups") > > >>> id = Column("id", Integer, primary_key=True) > >>> title = Column("title", String(50)) > > >&
[sqlalchemy] Re: Weird behavior
I think I see the error. Those are the whole tables: class User(rdb.Model): """Represents the user""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) email = Column("email", String(50)) password = Column("password", String(50)) hashed = Column("hashed", Boolean) military = Column("military", Boolean) agreedLicense = Column("agreed_license", Boolean) userGroupId = Column("user_group_id", Integer, ForeignKey("user_groups.id")) userGroup = relationship("UserGroup", uselist=False) channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users") mediaGroups = relationship("MediaGroup", secondary=user_media_groups, order_by="MediaGroup.title", backref="users") screens = relationship("Screen", secondary=user_screens, backref="users") screenGroups = relationship("ScreenGroup", secondary=user_screen_groups, order_by="ScreenGroup.title", backref="users") class UserGroup(rdb.Model): """Represents a group of users with the same features""" rdb.metadata(metadata) rdb.tablename("user_groups") id = Column("id", Integer, primary_key=True) title = Column("title", String(50)) users = relationship("User", order_by="User.name", cascade="all, delete", backref="user_groups") permissions = relationship("Permission", secondary=user_group_permissions, backref="user_groups") I have pretty similar tables and relations, but the different with other tables is I have this relation: userGroupId = Column("user_group_id", Integer, ForeignKey("user_groups.id")). So it seems every time when a user is created, it creates a new row in the user_groups and that row is related to that user. I think it's because of that relation. How could I avoid this? Thanks! On Dec 1, 6:35 pm, Michael Bayer wrote: > On Dec 1, 2010, at 5:46 PM, Alvaro Reinoso wrote: > > > > > Hello, > > > I have a system to manage users in my application, but I'm getting > > some troubles with it. > > > Every user has to belong to a group of users. One user can only be in > > one group. > > > I have those tables (inheriting from rdb.Model is basically the same > > thing than using sqlalchemy's declarative model) > > > class User(rdb.Model): > > """Represents the user""" > > rdb.metadata(metadata) > > rdb.tablename("users") > > > id = Column("id", Integer, primary_key=True) > > name = Column("name", String(50)) > > > > > userGroup = relationship("UserGroup", uselist=False) > > . > > > class UserGroup(rdb.Model): > > """Represents a group of users with the same features""" > > rdb.metadata(metadata) > > rdb.tablename("user_groups") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(50)) > > > users = relationship("User", order_by="User.name", cascade="all, > > delete, delete-orphan", backref="user_groups") > > > > > I have a script which migrate users from a pre-existing Zope DB > > (object-oriented): > > > def migrateUsers(): > > """Migrate all the users to the database""" > > session = rdb.Session() > > rScreens = session.query(Screen).all() > > rUserGroups = session.query(UserGroup).all() > > . > > > for oldUser in grok.getSite()['Users'].values(): > > user = User() > > .. > > for newGroup in rUserGroups: > > if newGroup.title == "superadmins": > > newGroup.users.append(user) > > .. > > > return > > > When I execute the script, the user_groups are properly created and > > the users are properly added to the user_groups they should belong to, > > but I get empty "group" entries in the database, and I don't know why > > > I have made some tests, and I've realized that I get an empty e
[sqlalchemy] Weird behavior
Hello, I have a system to manage users in my application, but I'm getting some troubles with it. Every user has to belong to a group of users. One user can only be in one group. I have those tables (inheriting from rdb.Model is basically the same thing than using sqlalchemy's declarative model) class User(rdb.Model): """Represents the user""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) userGroup = relationship("UserGroup", uselist=False) . class UserGroup(rdb.Model): """Represents a group of users with the same features""" rdb.metadata(metadata) rdb.tablename("user_groups") id = Column("id", Integer, primary_key=True) title = Column("title", String(50)) users = relationship("User", order_by="User.name", cascade="all, delete, delete-orphan", backref="user_groups") I have a script which migrate users from a pre-existing Zope DB (object-oriented): def migrateUsers(): """Migrate all the users to the database""" session = rdb.Session() rScreens = session.query(Screen).all() rUserGroups = session.query(UserGroup).all() . for oldUser in grok.getSite()['Users'].values(): user = User() .. for newGroup in rUserGroups: if newGroup.title == "superadmins": newGroup.users.append(user) .. return When I execute the script, the user_groups are properly created and the users are properly added to the user_groups they should belong to, but I get empty "group" entries in the database, and I don't know why I have made some tests, and I've realized that I get an empty entry (an empty user_group) every time I try to add a user to a user_group, but I don't know what is causing this behavior. Any hint will be appreciated. -- 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.
[sqlalchemy] How can I do this relation?
Hello, I have this table: class Region(rdb.Model): """Represents one region in the layout""" rdb.metadata(metadata) rdb.tablename("regions") id = Column("id", Integer, primary_key=True) title = Column("title", String(50)) .. channelId = Column("channel_id", Integer, ForeignKey("channel.id")) channel = relationship("Channel", uselist=False, backref="regions") One region can just contain one channel, but one channel could be in many regions. A region will never be accessed by a channel. However, Channel could be accessed by a region, so I need that relationship in region. Is that relationship OK? If not, how can I make it? Thanks! -- 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.
[sqlalchemy] Problem deleting an item
Hello all, I have these classes: class Screen(rdb.Model): """Represents the screen""" rdb.metadata(metadata) rdb.tablename("screens") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) .. crm = relationship("CRM", uselist=False, backref="screens") class CRM(rdb.Model): """Represents the CRM Tab""" rdb.metadata(metadata) rdb.tablename("crms") id = Column("id", Integer, ForeignKey("screens.id"), primary_key=True) title = Column("title", String(50)) contactInformation = relationship("CRMContactInformation", uselist=False, backref="crms") endpointConfiguration = relationship("CRMEndpointConfiguration", uselist=False, backref="crms") location = relationship("CRMLocation", uselist=False, backref="crms") slaEvent = relationship("CRMSLAEvent", uselist=False, backref="crms") notes = relationship("CRMNote", uselist=True, backref="crms") log = relationship("CRMLog", uselist=True, backref="crms") I get this error when trying to delele a screen object: session.delete(screen) AssertionError: Dependency rule tried to blank-out primary key column 'crms.id' on instance '' Thanks! -- 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.
[sqlalchemy] Re: Problems when querying the database
Fixed it! On Nov 22, 10:14 am, Alvaro Reinoso wrote: > So what do you suggest to get the instance by title? > > I can query the database by title to get the id and then query again > to get the instance by id. What do you think? > > On Nov 17, 1:10 pm, Michael Bayer wrote: > > > On Nov 16, 2010, at 3:56 PM, Alvaro Reinoso wrote: > > > > Hi all, > > > > I have a problem when querying the database: > > > > This channel class: > > > > class Channel(rdb.Model): > > > """Represents both complex channels and trivial ones (media)""" > > > rdb.metadata(metadata) > > > rdb.tablename("channels") > > > > id = Column("id", Integer, primary_key=True) > > > title = Column("title", String(100)) > > > > > > > items = relationship("MediaItem", secondary=channel_items, > > > order_by="MediaItem.position", backref="channels") > > > > I get the proper channel object if I do: > > > > channel = session.query(Channel).filter(Channel.title == title) > > > filter() always returns a Query object, not an instance. So there is no > > difference here between the call above and the one on MediaGroup, as far as > > the return result being a Query. > > > > And this is my mediaGroup class: > > > > class MediaGroup(rdb.Model): > > > """Represents MediaGroup class. Contains channels and other media > > > groups""" > > > rdb.metadata(metadata) > > > rdb.tablename("media_groups") > > > > id = Column("id", Integer, primary_key=True) > > > title = Column("title", String(100)) > > > > > > > channels = relationship("Channel", secondary=media_group_channels, > > > order_by="Channel.titleView", backref="media_groups") > > > mediaGroups = relationship("MediaGroup", > > > secondary=media_group_groups, order_by="MediaGroup.title", > > > primaryjoin=lambda: MediaGroup.id == > > > media_group_groups.c.media_groupA_id, > > > secondaryjoin=lambda: MediaGroup.id == > > > media_group_groups.c.media_groupB_id, > > > backref="media_groups") > > > > I get the Query object object if I do: > > > > mediaGroup = session.query(MediaGroup).filter(MediaGroup.title == > > > title) > > > > I don't know if it's because of the relationships but I tried without > > > mediaGroups relation, and I didn't work either. > > > > Any idea?? > > > > Thanks! > > > > -- > > > 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 > > > athttp://groups.google.com/group/sqlalchemy?hl=en. -- 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.
[sqlalchemy] Re: Problems when querying the database
So what do you suggest to get the instance by title? I can query the database by title to get the id and then query again to get the instance by id. What do you think? On Nov 17, 1:10 pm, Michael Bayer wrote: > On Nov 16, 2010, at 3:56 PM, Alvaro Reinoso wrote: > > > > > Hi all, > > > I have a problem when querying the database: > > > This channel class: > > > class Channel(rdb.Model): > > """Represents both complex channels and trivial ones (media)""" > > rdb.metadata(metadata) > > rdb.tablename("channels") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > > > > items = relationship("MediaItem", secondary=channel_items, > > order_by="MediaItem.position", backref="channels") > > > I get the proper channel object if I do: > > > channel = session.query(Channel).filter(Channel.title == title) > > filter() always returns a Query object, not an instance. So there is no > difference here between the call above and the one on MediaGroup, as far as > the return result being a Query. > > > > > And this is my mediaGroup class: > > > class MediaGroup(rdb.Model): > > """Represents MediaGroup class. Contains channels and other media > > groups""" > > rdb.metadata(metadata) > > rdb.tablename("media_groups") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > > > > channels = relationship("Channel", secondary=media_group_channels, > > order_by="Channel.titleView", backref="media_groups") > > mediaGroups = relationship("MediaGroup", > > secondary=media_group_groups, order_by="MediaGroup.title", > > primaryjoin=lambda: MediaGroup.id == > > media_group_groups.c.media_groupA_id, > > secondaryjoin=lambda: MediaGroup.id == > > media_group_groups.c.media_groupB_id, > > backref="media_groups") > > > I get the Query object object if I do: > > > mediaGroup = session.query(MediaGroup).filter(MediaGroup.title == > > title) > > > I don't know if it's because of the relationships but I tried without > > mediaGroups relation, and I didn't work either. > > > Any idea?? > > > Thanks! > > > -- > > 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 > > athttp://groups.google.com/group/sqlalchemy?hl=en. -- 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.
[sqlalchemy] Re: Weird error when adding a new object
Got it. I just change session.add(screenGroup) to session.merge(screenGroup) and it works. Thank you for you help, it's always really useful. On Nov 19, 3:10 pm, Michael Bayer wrote: > The most suspicious thing is self.__dict__['foo'] = list() as well as the > direct access to self.__dict__['foo']. If "self" is a mapped object, then > thats your issue. > > Also note this is still an out of context cut-and-paste, if you really want > me to figure it out it has to be an isolated test script. > > On Nov 19, 2010, at 2:49 PM, Alvaro Reinoso wrote: > > > Ok, This is the code: > > > �...@staticmethod > > def insert(string, mode): > > """Insert a new item given a string""" > > screenGroup = ScreenGroup() > > session = rdb.Session() > > > try: > > if mode == "XML": > > screenGroup.fromXML(string) > > elif mode == "JSON": > > screenGroup.fromJSON(string) > > if screenGroup.id == None: > > session.add(screenGroup) > > else: > > screenGroup = session.merge(screenGroup) > > > session.flush() > > result = "Successful:" + str(screenGroup.id) + "," + > > screenGroup.title > > return result > > except Exception, e: > > log.warn("::ScreenGroupManager, insert > The error is " > > + str(e)) > > return "Error connecting to the database. Please > > try again > > later." > > > return "Error connecting to the database. Please try again > > later." > > > This is the function where it gets the error. When I already have the > > item and I merge It works out. However, if it's a new item, breaks. > > This anothe fromXML function: > > > def fromXML(self, data): > > """Unserializes this class from an XML formatted file or > > string.""" > > root = "" > > try: > > if(data.endswith(".xml")): > > doc = etree.parse(data) > > root = doc.getroot() > > else: > > root = etree.XML(data) > > except etree.XMLSyntaxError, e: > > print e > > pass > > > if not type(root) == type(etree.XML("test")): > > return > > > if root.tag == "screenGroup": > > for child in root.iterchildren(): > > if child.tag == "screens" or child.tag == > > "screenGroups": > > if child.text: > > items = child.text.split(",") > > self.__dict__[child.tag] = list() > > for itemId in items: > > if child.tag == > > "screens": > > item = > > ScreenManager.getScreenById(itemId) > > else: > > item = > > ScreenGroupManager.getGroupScreenById(itemId) > > > > self.__dict__[child.tag].append(item) > > else: > > self.setAttr(child.tag, child.text) > > > ScreenManager.getScreenById(itemId) and > > ScreenGroupManager.getGroupScreenById(itemId) just get the item from > > the database (session.query(Screen).get(int(itemId))). > > > This is the XML string : Group 10 > title>4,3 > screenGroup> > > > Thanks! > > > On Nov 18, 7:07 pm, Michael Bayer wrote: > >> looks fine to me, would need full stack trace + single script file of > >> runnable, reproducing code, thanks. > > >> On Nov 18, 2010, at 6:37 PM, Alvaro Reinoso wrote: > > >>> Hello, > > >>> When trying to add a new item doing: > > >>> session = session.add(mediaGroup) > > >>&g
[sqlalchemy] Re: Weird error when adding a new object
Ok, This is the code: @staticmethod def insert(string, mode): """Insert a new item given a string""" screenGroup = ScreenGroup() session = rdb.Session() try: if mode == "XML": screenGroup.fromXML(string) elif mode == "JSON": screenGroup.fromJSON(string) if screenGroup.id == None: session.add(screenGroup) else: screenGroup = session.merge(screenGroup) session.flush() result = "Successful:" + str(screenGroup.id) + "," + screenGroup.title return result except Exception, e: log.warn("::ScreenGroupManager, insert > The error is " + str(e)) return "Error connecting to the database. Please try again later." return "Error connecting to the database. Please try again later." This is the function where it gets the error. When I already have the item and I merge It works out. However, if it's a new item, breaks. This anothe fromXML function: def fromXML(self, data): """Unserializes this class from an XML formatted file or string.""" root = "" try: if(data.endswith(".xml")): doc = etree.parse(data) root = doc.getroot() else: root = etree.XML(data) except etree.XMLSyntaxError, e: print e pass if not type(root) == type(etree.XML("test")): return if root.tag == "screenGroup": for child in root.iterchildren(): if child.tag == "screens" or child.tag == "screenGroups": if child.text: items = child.text.split(",") self.__dict__[child.tag] = list() for itemId in items: if child.tag == "screens": item = ScreenManager.getScreenById(itemId) else: item = ScreenGroupManager.getGroupScreenById(itemId) self.__dict__[child.tag].append(item) else: self.setAttr(child.tag, child.text) ScreenManager.getScreenById(itemId) and ScreenGroupManager.getGroupScreenById(itemId) just get the item from the database (session.query(Screen).get(int(itemId))). This is the XML string : Group 104,3 Thanks! On Nov 18, 7:07 pm, Michael Bayer wrote: > looks fine to me, would need full stack trace + single script file of > runnable, reproducing code, thanks. > > On Nov 18, 2010, at 6:37 PM, Alvaro Reinoso wrote: > > > Hello, > > > When trying to add a new item doing: > > > session = session.add(mediaGroup) > > > I got this error: > > > Module sqlalchemy.orm.attributes:834 in get_collection > > return getattr(user_data, '_sa_adapter') > > class GenericBackrefExtension(interfaces.AttributeExtension):>> > > return getattr(user_data, '_sa_adapter') > > > "AttributeError: 'list' object has no attribute '_sa_adapter'" > > > This object's class: > > > class ScreenGroup(rdb.Model): > > """The ScreenGroup is a class derived from ScreenGroup, it is used to > > control users within a group""" > > rdb.metadata(metadata) > > rdb.tablename("screen_groups") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > parents = Column("parents", String(512)) > > > screens = relationship("Screen", secondary=group_screens, > > order_by="Screen.title", backref="screen_groups") > > screenGroups = relationship("ScreenGroup", > > secondary=screen_group_groups, order_by="Scr
[sqlalchemy] Weird error when adding a new object
Hello, When trying to add a new item doing: session = session.add(mediaGroup) I got this error: Module sqlalchemy.orm.attributes:834 in get_collection return getattr(user_data, '_sa_adapter') class GenericBackrefExtension(interfaces.AttributeExtension):>> return getattr(user_data, '_sa_adapter') "AttributeError: 'list' object has no attribute '_sa_adapter'" This object's class: class ScreenGroup(rdb.Model): """The ScreenGroup is a class derived from ScreenGroup, it is used to control users within a group""" rdb.metadata(metadata) rdb.tablename("screen_groups") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) parents = Column("parents", String(512)) screens = relationship("Screen", secondary=group_screens, order_by="Screen.title", backref="screen_groups") screenGroups = relationship("ScreenGroup", secondary=screen_group_groups, order_by="ScreenGroup.title", primaryjoin=lambda: ScreenGroup.id == screen_group_groups.c.screen_groupA_id, secondaryjoin=lambda: ScreenGroup.id == screen_group_groups.c.screen_groupB_id, backref="screen_groups") Thanks in advance! -- 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.
[sqlalchemy] Problems when querying the database
Hi all, I have a problem when querying the database: This channel class: class Channel(rdb.Model): """Represents both complex channels and trivial ones (media)""" rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) items = relationship("MediaItem", secondary=channel_items, order_by="MediaItem.position", backref="channels") I get the proper channel object if I do: channel = session.query(Channel).filter(Channel.title == title) And this is my mediaGroup class: class MediaGroup(rdb.Model): """Represents MediaGroup class. Contains channels and other media groups""" rdb.metadata(metadata) rdb.tablename("media_groups") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) channels = relationship("Channel", secondary=media_group_channels, order_by="Channel.titleView", backref="media_groups") mediaGroups = relationship("MediaGroup", secondary=media_group_groups, order_by="MediaGroup.title", primaryjoin=lambda: MediaGroup.id == media_group_groups.c.media_groupA_id, secondaryjoin=lambda: MediaGroup.id == media_group_groups.c.media_groupB_id, backref="media_groups") I get the Query object object if I do: mediaGroup = session.query(MediaGroup).filter(MediaGroup.title == title) I don't know if it's because of the relationships but I tried without mediaGroups relation, and I didn't work either. Any idea?? Thanks! -- 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.
[sqlalchemy] Weird error when I add a new attribute to one class
Hello, I got a weird error when I try to create a new object. Before It worked without any problem, but I got this error after adding a new attribute to the User class. This attribute is related to Screen in a relation many to many through user_screens. This is the error: "InvalidRequestError: One or more mappers failed to compile. Exception was probably suppressed within a hasattr() call. Message was: One or more mappers failed to compile. Exception was probably suppressed within a hasattr() call. Message was: Class 'zeppelinlib.screen.ScreenTest.Screen' is not mapped" These are the classes: class Screen(rdb.Model): """Set up screens table in the database""" rdb.metadata(metadata) rdb.tablename("screens") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) ip = Column("ip", String(20)) ... user_screens = Table( "user_screens", metadata, Column("user_id", Integer, ForeignKey("users.id")), Column("screen_id", Integer, ForeignKey("screens.id")) ) class User(rdb.Model): """Set up users table in the database""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) ... group = relationship("UserGroup", uselist=False) channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users") mediaGroups = relationship("MediaGroup", secondary=user_media_groups, order_by="MediaGroup.title", backref="users") screens = relationship("Screen", secondary=user_screens, backref="users") I might not added new relation to user because I really don't know what the problem is... Thanks in avance! -- 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.
[sqlalchemy] Re: Best way to get data from database
Thank you Eric! It's good approach and I'm gonna keep it in mind. I can get the data in hidden fields and just use the REST API to do POST, PUT and DELETE. On Oct 29, 10:33 pm, Eric Ongerth wrote: > I understand your question if you are getting different data from the > server in the two database accesses. But if you are loading the exact > same data twice for a page load, you should try to eliminate that > redundancy instead of finding a plan to perform the redundancy in the > best way. > > If it's the identical data twice, then why not render it into the page > when you are rendering the HTML... you can render hidden fields, CDATA > sections, regions of javascript containing any data structure you > need, etc. > > It's a confusing question because if it's two different DB requests > then you wouldn't be inquiring about caching for this purpose, but if > it's two identical DB requests I suspect you already would have > realized that the data could easily be encoded in the original page > render. > > On Oct 28, 4:22 pm, Alvaro Reinoso wrote: > > > Hey guys, > > > I have a doubt. I need to get the data from the sever twice every time > > when I load a page, one to render the HTML and another one to get the > > data for client side (javascript). > > > So I don't know exactly what it's the best way and fastest. I was > > trying to implement a session object and store the data once using > > joinedload loading technique. When the data is in the client side, to > > kill the session object. > > > Another one it's to call the database twice. > > > I don't know which one is faster and better because I don't know if > > the database or server stores the first call in memory. If so it's not > > like to call the database twice, right? > > > And if the second choice is better which loading technique > > (joinedload, eagerload or subqueryload) is better to use. > > > Every call could be a bunch of data. > > > Any help could be really useful. > > > Thanks in advance! -- 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.
[sqlalchemy] Best way to get data from database
Hey guys, I have a doubt. I need to get the data from the sever twice every time when I load a page, one to render the HTML and another one to get the data for client side (javascript). So I don't know exactly what it's the best way and fastest. I was trying to implement a session object and store the data once using joinedload loading technique. When the data is in the client side, to kill the session object. Another one it's to call the database twice. I don't know which one is faster and better because I don't know if the database or server stores the first call in memory. If so it's not like to call the database twice, right? And if the second choice is better which loading technique (joinedload, eagerload or subqueryload) is better to use. Every call could be a bunch of data. Any help could be really useful. Thanks in advance! -- 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.
[sqlalchemy] Re: Problems creating tables one to one relation
It's fixed. I was my mistake, I didn't realize it. Thank you! On Oct 25, 5:19 pm, Michael Bayer wrote: > On Oct 25, 2010, at 4:59 PM, Alvaro Reinoso wrote: > > > I think it should be another problem because I have a file where I > > initialize all the tables, so that file contains all the tables. The > > tables are created properly, but when I try to create a Screen object > > (the main class, Screen -> CRM -> CRMContactInformation), I get this > > error: > > looks like you are passing a Table object, or the name of one, where a mapped > class is expected. this would be the cause of that: > > contactInformation = relationship("crm_contact_informations", uselist=False, > backref="crms") > > "CRMContactInformation" > > > > > UnmappedClassError: Class 'Table('crm_contact_informations', > > MetaData(None), Column('id', Integer(), ForeignKey('crms.id'), > > table=, primary_key=True, nullable=False), > > Column('owner', String(length=50, convert_unicode=False, > > assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), > > table=), Column('owner_phone', > > String(length=20, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), Column('owner_email', > > String(length=50, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), Column('store_manager', > > String(length=50, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), Column('store_phone', > > String(length=20, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), Column('store_email', > > String(length=50, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), Column('it_manager', > > String(length=50, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), Column('it_manager_phone', > > String(length=20, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), Column('it_manager_email', > > String(length=50, convert_unicode=False, assert_unicode=None, > > unicode_error=None, _warn_on_bytestring=False), > > table=), schema=None)' is not mapped > > > On Oct 25, 3:58 pm, Michael Bayer wrote: > >> all modules which include mapped classes must be imported before you > >> attempt to initialize the mappings. If class A references "B", but "class > >> B" doesn't exist, you get errors like that, so importing the modules that > >> contain both class A and B solves the issue. > > >> On Oct 25, 2010, at 2:55 PM, Alvaro Reinoso wrote: > > >>> Hello, > > >>> I get errors when I try to create tables one to one relation. Screen > >>> contains crm and crm contains more classes. The relation is one to one > >>> between crm, so I want to use the screen id as primary key in crm. And > >>> the relation is one to one between crm and some classes, I just added > >>> one class as example, so children of crm must contain a screen id as a > >>> primary key. When I try to make the last relation, it's when it > >>> breaks. I tried to use both, crm id and screen id. > > >>> I didn't work. I get errors such as, "UnmappedClassError" when I try > >>> to use crm id in ContactInformation, and "Could not determine join > >>> condition between parent/child tables on relationship > >>> CRM.contactInformation. Specify a 'primaryjoin' expression. If this is > >>> a many-to-many relationship, 'secondaryjoin' is needed as well" when I > >>> try to use screen id in ContactInformation. > > >>> These are my classes: > > >>> class Screen(rdb.Model): > >>> """Set up screens table in the database""" > >>> rdb.metadata(metadata) > >>> rdb.tablename("screens") > > >>> id = Column("id", Integer, primary_key=True) > >>> title = Column("title", String(100)) > >>> > > >>> crm = relationship("CRM", uselist=False, backref="screens") > >
[sqlalchemy] Re: Problems creating tables one to one relation
I think it should be another problem because I have a file where I initialize all the tables, so that file contains all the tables. The tables are created properly, but when I try to create a Screen object (the main class, Screen -> CRM -> CRMContactInformation), I get this error: UnmappedClassError: Class 'Table('crm_contact_informations', MetaData(None), Column('id', Integer(), ForeignKey('crms.id'), table=, primary_key=True, nullable=False), Column('owner', String(length=50, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('owner_phone', String(length=20, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('owner_email', String(length=50, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('store_manager', String(length=50, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('store_phone', String(length=20, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('store_email', String(length=50, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('it_manager', String(length=50, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('it_manager_phone', String(length=20, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), Column('it_manager_email', String(length=50, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), table=), schema=None)' is not mapped On Oct 25, 3:58 pm, Michael Bayer wrote: > all modules which include mapped classes must be imported before you attempt > to initialize the mappings. If class A references "B", but "class B" doesn't > exist, you get errors like that, so importing the modules that contain both > class A and B solves the issue. > > On Oct 25, 2010, at 2:55 PM, Alvaro Reinoso wrote: > > > Hello, > > > I get errors when I try to create tables one to one relation. Screen > > contains crm and crm contains more classes. The relation is one to one > > between crm, so I want to use the screen id as primary key in crm. And > > the relation is one to one between crm and some classes, I just added > > one class as example, so children of crm must contain a screen id as a > > primary key. When I try to make the last relation, it's when it > > breaks. I tried to use both, crm id and screen id. > > > I didn't work. I get errors such as, "UnmappedClassError" when I try > > to use crm id in ContactInformation, and "Could not determine join > > condition between parent/child tables on relationship > > CRM.contactInformation. Specify a 'primaryjoin' expression. If this is > > a many-to-many relationship, 'secondaryjoin' is needed as well" when I > > try to use screen id in ContactInformation. > > > These are my classes: > > > class Screen(rdb.Model): > > """Set up screens table in the database""" > > rdb.metadata(metadata) > > rdb.tablename("screens") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > > > > crm = relationship("CRM", uselist=False, backref="screens") > > > class CRM(rdb.Model): > > """Set up crm table in the database""" > > rdb.metadata(metadata) > > rdb.tablename("crms") > > > id = Column("id", Integer, ForeignKey("screens.id"), > > primary_key=True) > > > contactInformation = relationship("crm_contact_informations", > > uselist=False, backref="crms") > > > > > class CRMContactInformation(rdb.Model): > > """Set up crm contact information table in the database""" > > rdb.metadata(metadata) > > rdb.tablename("crm_contact_informations") > > > id = Column("id", Integer, ForeignKey("screens.id"), > > primary_key=True) > > owner = Column("owner", String(50)) > > ... > > > -- > > 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 > > athttp://groups.google.com/group/sqlalchemy?hl=en. -- 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.
[sqlalchemy] Problems creating tables one to one relation
Hello, I get errors when I try to create tables one to one relation. Screen contains crm and crm contains more classes. The relation is one to one between crm, so I want to use the screen id as primary key in crm. And the relation is one to one between crm and some classes, I just added one class as example, so children of crm must contain a screen id as a primary key. When I try to make the last relation, it's when it breaks. I tried to use both, crm id and screen id. I didn't work. I get errors such as, "UnmappedClassError" when I try to use crm id in ContactInformation, and "Could not determine join condition between parent/child tables on relationship CRM.contactInformation. Specify a 'primaryjoin' expression. If this is a many-to-many relationship, 'secondaryjoin' is needed as well" when I try to use screen id in ContactInformation. These are my classes: class Screen(rdb.Model): """Set up screens table in the database""" rdb.metadata(metadata) rdb.tablename("screens") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) crm = relationship("CRM", uselist=False, backref="screens") class CRM(rdb.Model): """Set up crm table in the database""" rdb.metadata(metadata) rdb.tablename("crms") id = Column("id", Integer, ForeignKey("screens.id"), primary_key=True) contactInformation = relationship("crm_contact_informations", uselist=False, backref="crms") class CRMContactInformation(rdb.Model): """Set up crm contact information table in the database""" rdb.metadata(metadata) rdb.tablename("crm_contact_informations") id = Column("id", Integer, ForeignKey("screens.id"), primary_key=True) owner = Column("owner", String(50)) ... -- 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.
[sqlalchemy] Re: Recursive problem
I solved the problem delaying the imports like: from zeppelinlib.screen.ScreenTest import Screen CRMContactInformation.id = Column("id", Integer, ForeignKey(Screen.id), primary_key=True) On Oct 25, 11:18 am, Alvaro Reinoso wrote: > Hey guys, > > I have a problem when I import classes from one to another. I have > those classes in different modules: > > crm.py > > from CRMContactInformation import CRMContactInformation > > class CRM(rdb.Model): > """Set up crm table in the database""" > rdb.metadata(metadata) > rdb.tablename("crms") > > id = Column("id", Integer, ForeignKey("screens.id"), > primary_key=True) > screen_id = Column("screen_id", Integer, ) > > contactInformation = relationship(CRMContactInformation, > userlist=False, backref="crms") > > > CRMContactInformation.py > > from CRM import CRM > > class CRMContactInformation(rdb.Model): > """Set up crm contact information table in the database""" > rdb.metadata(metadata) > rdb.tablename("crm_contact_informations") > > id = Column("id", Integer, ForeignKey(CRM.id), primary_key=True) > owner = Column("owner", String(50)) > . > > As you can see, I have a recursive problem because I import > CRMContactInformation in CRM and CRM in CRMContactInformation. I got > this error or similar: > > “AttributeError: ‘module’ object has no attribute ” > > I tried to change the imports importing the whole path. It didn't work > out either. > > Is there any way I can use the metadata object to access the > attributes of the tables? or another way to solve this? > > Thanks in advance! -- 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.
[sqlalchemy] Recursive problem
Hey guys, I have a problem when I import classes from one to another. I have those classes in different modules: crm.py from CRMContactInformation import CRMContactInformation class CRM(rdb.Model): """Set up crm table in the database""" rdb.metadata(metadata) rdb.tablename("crms") id = Column("id", Integer, ForeignKey("screens.id"), primary_key=True) screen_id = Column("screen_id", Integer, ) contactInformation = relationship(CRMContactInformation, userlist=False, backref="crms") CRMContactInformation.py from CRM import CRM class CRMContactInformation(rdb.Model): """Set up crm contact information table in the database""" rdb.metadata(metadata) rdb.tablename("crm_contact_informations") id = Column("id", Integer, ForeignKey(CRM.id), primary_key=True) owner = Column("owner", String(50)) . As you can see, I have a recursive problem because I import CRMContactInformation in CRM and CRM in CRMContactInformation. I got this error or similar: “AttributeError: ‘module’ object has no attribute ” I tried to change the imports importing the whole path. It didn't work out either. Is there any way I can use the metadata object to access the attributes of the tables? or another way to solve this? Thanks in advance! -- 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.
[sqlalchemy] dynamic load better choice than joinedload?
Hello, I'd like to know what the best choice is. This is what I do in my system: I'm using grok server and python on the server side; and javascript on the client side. I store all the user data in a session object and this data gets called twice, one to render the HTML on the server side and another to send the data to the client side because the client side is dynamic. I'm using joinedload right know but I know I can't use operations such as, append and remove, when the user update or add something. The timeout of the session object is one hour. I'd like to know if it's better to use dynamic load because I guess with dynamic load you have an open connection to the database, so it might take many resources. The user object might contain a big collections of data. Thanks in advance! -- 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.
[sqlalchemy] Re: Updating a detached object
Channel is type of object that I use in my application. I guess I think how I can solve this problem. I load some list of object using the option joinedload. I store those lists in HTTP session object, so I can manipulate them through the user session. When I update some object from those lists, how can I reconnect that object with the database to reflect the changes? On Sep 13, 2:47 pm, Michael Bayer wrote: > On Sep 13, 2010, at 2:31 PM, Alvaro Reinoso wrote: > > > Yes, I've done that. I doesn't work either. > > > for chan in channels: > > if chan.id == channel.id: > > chan = session.merge(channel) > > break > > i dont understand the context of that code (what's "channel") ? > > This is how a basic merge works: > > def merge_new_data(some_xml): > my_objects = parse_xml(some_xml) > > # at this point, every object in "my_objects" should > # have a primary key, as well as every child of every element, > # all the way down. Existing primary keys must be fully populated, > # that's your job. This is the intricate part, obviously. But you don't > # merge anything here, just get the PKs filled in. > > # then you merge the whole thing. merge() cascades along all > # relationships. The rule is simple - if PK is present and exists in the > DB, it > # updates. otherwise, it inserts. > > for obj in my_objects: > Session.merge(obj) > Session.commit() > > # done > > > > > On Sep 13, 2:27 pm, Michael Bayer wrote: > >> On Sep 13, 2010, at 2:13 PM, Alvaro Reinoso wrote: > > >>> If I merge the updated channel like you can see in this piece of code > >>> it's working: > > >>> def insertXML(channels, strXml): > >>> """Insert a new channel given XML string""" > >>> channel = Channel() > >>> session = rdb.Session() > > >>> channel.fromXML(strXml) > >>> fillChannelTemplate(channel, channels) > >>> for item in channel.items: > >>> if item.id == 0: > >>> item.id = None > >>> break > >>> session.merge(channel) > > >>> for chan in channels: > >>> if chan.id == channel.id: > >>> chan.items.append(item) > >>> break > > >>> My problem is I'm using channels, it's a list of channels which I save > >>> it in HTTP session object. The channels list is a detached object > >>> which I get using joinload option. So in this case, I update the > >>> object correctly in database, but It isn't persistent in channels if I > >>> do this: > > >>> for chan in channels: > >>> if chan.id == channel.id: > >>> chan.items.append(item) > >>> break > > >>> Do you have any idea how I can solve this problem? or another > >>> approach? > > >> here: > > >>> session.merge(channel) > > >> use the return value of merge(): > > >> channel = session.merge(channel) > > >> the returned channel plus all children is the fully merged result. > > >>> Thanks! > > >>> On Sep 10, 5:09 pm, Michael Bayer wrote: > >>>> On Sep 10, 2010, at 2:57 PM, Alvaro Reinoso wrote: > > >>>>> Hello guys, > > >>>>> I have this table: > > >>>>> class Channel(rdb.Model): > >>>>> rdb.metadata(metadata) > >>>>> rdb.tablename("channels") > > >>>>> id = Column("id", Integer, primary_key=True) > >>>>> title = Column("title", String(100)) > >>>>> hash = Column("hash", String(50)) > >>>>> runtime = Column("runtime", Float) > > >>>>> items = relationship(MediaItem, secondary="channel_items", > >>>>> order_by=MediaItem.position, backref="channels") > > >>>>> I have a list
[sqlalchemy] Re: Updating a detached object
Channel is just type of object. I realize what my problem is. I don't know why my object isn't saved correctly. for chan in channels: if chan.id == channel.id: > >chan = session.merge(channel) > >break On Sep 13, 2:47 pm, Michael Bayer wrote: > On Sep 13, 2010, at 2:31 PM, Alvaro Reinoso wrote: > > > Yes, I've done that. I doesn't work either. > > > for chan in channels: > > if chan.id == channel.id: > > chan = session.merge(channel) > > break > > i dont understand the context of that code (what's "channel") ? > > This is how a basic merge works: > > def merge_new_data(some_xml): > my_objects = parse_xml(some_xml) > > # at this point, every object in "my_objects" should > # have a primary key, as well as every child of every element, > # all the way down. Existing primary keys must be fully populated, > # that's your job. This is the intricate part, obviously. But you don't > # merge anything here, just get the PKs filled in. > > # then you merge the whole thing. merge() cascades along all > # relationships. The rule is simple - if PK is present and exists in the > DB, it > # updates. otherwise, it inserts. > > for obj in my_objects: > Session.merge(obj) > Session.commit() > > # done > > > > > On Sep 13, 2:27 pm, Michael Bayer wrote: > >> On Sep 13, 2010, at 2:13 PM, Alvaro Reinoso wrote: > > >>> If I merge the updated channel like you can see in this piece of code > >>> it's working: > > >>> def insertXML(channels, strXml): > >>> """Insert a new channel given XML string""" > >>> channel = Channel() > >>> session = rdb.Session() > > >>> channel.fromXML(strXml) > >>> fillChannelTemplate(channel, channels) > >>> for item in channel.items: > >>> if item.id == 0: > >>> item.id = None > >>> break > >>> session.merge(channel) > > >>> for chan in channels: > >>> if chan.id == channel.id: > >>> chan.items.append(item) > >>> break > > >>> My problem is I'm using channels, it's a list of channels which I save > >>> it in HTTP session object. The channels list is a detached object > >>> which I get using joinload option. So in this case, I update the > >>> object correctly in database, but It isn't persistent in channels if I > >>> do this: > > >>> for chan in channels: > >>> if chan.id == channel.id: > >>> chan.items.append(item) > >>> break > > >>> Do you have any idea how I can solve this problem? or another > >>> approach? > > >> here: > > >>> session.merge(channel) > > >> use the return value of merge(): > > >> channel = session.merge(channel) > > >> the returned channel plus all children is the fully merged result. > > >>> Thanks! > > >>> On Sep 10, 5:09 pm, Michael Bayer wrote: > >>>> On Sep 10, 2010, at 2:57 PM, Alvaro Reinoso wrote: > > >>>>> Hello guys, > > >>>>> I have this table: > > >>>>> class Channel(rdb.Model): > >>>>> rdb.metadata(metadata) > >>>>> rdb.tablename("channels") > > >>>>> id = Column("id", Integer, primary_key=True) > >>>>> title = Column("title", String(100)) > >>>>> hash = Column("hash", String(50)) > >>>>> runtime = Column("runtime", Float) > > >>>>> items = relationship(MediaItem, secondary="channel_items", > >>>>> order_by=MediaItem.position, backref="channels") > > >>>>> I have a list of channels, but they are detached objects. I get them &g
[sqlalchemy] Re: Updating a detached object
Yes, I've done that. I doesn't work either. for chan in channels: if chan.id == channel.id: chan = session.merge(channel) break On Sep 13, 2:27 pm, Michael Bayer wrote: > On Sep 13, 2010, at 2:13 PM, Alvaro Reinoso wrote: > > > > > If I merge the updated channel like you can see in this piece of code > > it's working: > > > def insertXML(channels, strXml): > > """Insert a new channel given XML string""" > > channel = Channel() > > session = rdb.Session() > > > channel.fromXML(strXml) > > fillChannelTemplate(channel, channels) > > for item in channel.items: > > if item.id == 0: > > item.id = None > > break > > session.merge(channel) > > > for chan in channels: > > if chan.id == channel.id: > > chan.items.append(item) > > break > > > My problem is I'm using channels, it's a list of channels which I save > > it in HTTP session object. The channels list is a detached object > > which I get using joinload option. So in this case, I update the > > object correctly in database, but It isn't persistent in channels if I > > do this: > > > for chan in channels: > > if chan.id == channel.id: > > chan.items.append(item) > > break > > > Do you have any idea how I can solve this problem? or another > > approach? > > here: > > > session.merge(channel) > > use the return value of merge(): > > channel = session.merge(channel) > > the returned channel plus all children is the fully merged result. > > > > > Thanks! > > > On Sep 10, 5:09 pm, Michael Bayer wrote: > >> On Sep 10, 2010, at 2:57 PM, Alvaro Reinoso wrote: > > >>> Hello guys, > > >>> I have this table: > > >>> class Channel(rdb.Model): > >>> rdb.metadata(metadata) > >>> rdb.tablename("channels") > > >>> id = Column("id", Integer, primary_key=True) > >>> title = Column("title", String(100)) > >>> hash = Column("hash", String(50)) > >>> runtime = Column("runtime", Float) > > >>> items = relationship(MediaItem, secondary="channel_items", > >>> order_by=MediaItem.position, backref="channels") > > >>> I have a list of channels, but they are detached objects. I get them > >>> using joinedload option because I maniputale those objects sometimes. > >>> When I do that, I update the object. > > >>> This time, I'm trying to add a new item to a detached channel object. > >>> This is the code: > > >>> def insertXML(channels, strXml): > >>> """Insert a new channel given XML string""" > >>> channel = Channel() > >>> session = rdb.Session() > >>> result = "" > > >>> channel.fromXML(strXml) > >>> fillChannelTemplate(channel, channels) > >>> if channel.id == 0: > >>> session.add(channel) > >>> session.flush() > >>> channels.append(channel) > >>> else: > >>> for chan in channels: > >>> if chan.id == channel.id: > >>> chan.runtime = channel.runtime > >>> chan.modified = datetime.date.today() > > >>> for item in channel.items: > >>> if item.id == 0: > >>> chan.items.append(item) > > >>> session.merge(chan) > > >>> The item is inserted in the database, but It doesn't create the > >>> relation in channel_items. > > >>> Besid
[sqlalchemy] Re: Updating a detached object
If I merge the updated channel like you can see in this piece of code it's working: def insertXML(channels, strXml): """Insert a new channel given XML string""" channel = Channel() session = rdb.Session() channel.fromXML(strXml) fillChannelTemplate(channel, channels) for item in channel.items: if item.id == 0: item.id = None break session.merge(channel) for chan in channels: if chan.id == channel.id: chan.items.append(item) break My problem is I'm using channels, it's a list of channels which I save it in HTTP session object. The channels list is a detached object which I get using joinload option. So in this case, I update the object correctly in database, but It isn't persistent in channels if I do this: for chan in channels: if chan.id == channel.id: chan.items.append(item) break Do you have any idea how I can solve this problem? or another approach? Thanks! On Sep 10, 5:09 pm, Michael Bayer wrote: > On Sep 10, 2010, at 2:57 PM, Alvaro Reinoso wrote: > > > > > Hello guys, > > > I have this table: > > > class Channel(rdb.Model): > > rdb.metadata(metadata) > > rdb.tablename("channels") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > hash = Column("hash", String(50)) > > runtime = Column("runtime", Float) > > > items = relationship(MediaItem, secondary="channel_items", > > order_by=MediaItem.position, backref="channels") > > > I have a list of channels, but they are detached objects. I get them > > using joinedload option because I maniputale those objects sometimes. > > When I do that, I update the object. > > > This time, I'm trying to add a new item to a detached channel object. > > This is the code: > > > def insertXML(channels, strXml): > > """Insert a new channel given XML string""" > > channel = Channel() > > session = rdb.Session() > > result = "" > > > channel.fromXML(strXml) > > fillChannelTemplate(channel, channels) > > if channel.id == 0: > > session.add(channel) > > session.flush() > > channels.append(channel) > > else: > > for chan in channels: > > if chan.id == channel.id: > > chan.runtime = channel.runtime > > chan.modified = datetime.date.today() > > > for item in channel.items: > > if item.id == 0: > > chan.items.append(item) > > > session.merge(chan) > > > The item is inserted in the database, but It doesn't create the > > relation in channel_items. > > > Besides, I get this error: > > > FlushError: New instance with identity key > > (, (152,)) conflicts > > with persistent instance > anytime you have that error you should be using merge() to merge state into > that which is already existing, the return value from merge() is then what > you need to use for your new state. I see you tried using merge earlier but > your issue is not clear. -- 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.
[sqlalchemy] Updating a detached object
Hello guys, I have this table: class Channel(rdb.Model): rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) hash = Column("hash", String(50)) runtime = Column("runtime", Float) items = relationship(MediaItem, secondary="channel_items", order_by=MediaItem.position, backref="channels") I have a list of channels, but they are detached objects. I get them using joinedload option because I maniputale those objects sometimes. When I do that, I update the object. This time, I'm trying to add a new item to a detached channel object. This is the code: def insertXML(channels, strXml): """Insert a new channel given XML string""" channel = Channel() session = rdb.Session() result = "" channel.fromXML(strXml) fillChannelTemplate(channel, channels) if channel.id == 0: session.add(channel) session.flush() channels.append(channel) else: for chan in channels: if chan.id == channel.id: chan.runtime = channel.runtime chan.modified = datetime.date.today() for item in channel.items: if item.id == 0: chan.items.append(item) session.merge(chan) The item is inserted in the database, but It doesn't create the relation in channel_items. Besides, I get this error: FlushError: New instance with identity key (, (152,)) conflicts with persistent instance http://groups.google.com/group/sqlalchemy?hl=en.
[sqlalchemy] Update a record in a table
I have some problems when I try to update information in some tables. For example, I have this table: class Channel(rdb.Model): rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) hash = Column("hash", String(50)) runtime = Column("runtime", Float) items = relationship(MediaItem, secondary="channel_items", order_by=MediaItem.position, backref="channels") And I have this code: def insertXML(channels, strXml): channel = Channel() session = rdb.Session() result = "" channel.fromXML(strXml) fillChannelTemplate(channel, channels) rChannel = session.query(Channel).get(channel.id) for chan in channels: if rChannel.id == channel.id: rChannel.runtime = channel.runtime for item in channel.items: if item.id == 0: rChannel.items.append(item) When I do "rChannel.items.append(item)", I got this error: "FlushError: New instance Channel at 0xaf6e48c with identity key zeppelinlib.channel.ChannelTest.Channel , (152,) conflicts with persistent instance Channel at 0xac2e8ac" However, this instruction is working "rChannel.runtime = channel.runtime". Besides, if I try to merge, the item is getting insert in database, but the relation between channel and item is not created. I also get the same error. Any idea? Thanks in advance! -- 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.
[sqlalchemy] Get read-only objects with session object
Hello, I have a complex database where user object is related almost to every table in some way. In a previous post, I asked how to get read-only objects. I found out I could use the option "joinedload" when I query database. It's working fine, but I have another problem. These are my tables: class User(rdb.Model): """Set up users table in the database""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) email = Column("email", String(50)) group = relationship("UserGroup") channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users") mediaGroups = relationship("MediaGroup", secondary=user_media_groups, order_by="MediaGroup.title", backref="users") class UserGroup(rdb.Model): """Set up user_groups table in the database""" rdb.metadata(metadata) rdb.tablename("user_groups") id = Column("id", Integer, primary_key=True) title = Column("title", String(50)) users = relationship("User", order_by="User.name", backref="user_groups") permissions = relationship("Permission", secondary=user_group_permissions, backref="user_groups") When I do: user = session.query(User).options(joinedload("group"), joinedload("channels"), joinedload("mediaGroups")).get(int(userId)) And when I try to get the users from the attribute group in user, I get this: "DetachedInstanceError: Parent instance is not bound to a Session; lazy load operation of attribute 'users' cannot proceed" So how can I get all the data related to user object without having this problem? I save my user object in the session object in the server, so I need in just one time to get all the data related to user. Thanks in advance! Alvaro -- 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.
[sqlalchemy] How to get read-only objects from database?
Hello, I'd like to query the database and get read-only objects with session object. I need to save the objects in my server and use them through the user session. If I use a object outside of the function that calls the database, I get this error: "DetachedInstanceError: Parent instance is not bound to a Session; lazy load operation of attribute 'items' cannot proceed" I don't need to make any change in those objects, so I don't need to load them again. Is there any way that I can get that? Thanks in advance! -- 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.
[sqlalchemy] Re: How to link one table to itself?
It's working properly with that relation: mediaGroup = relationship("MediaGroup", secondary=media_group_groups, order_by="MediaGroup.title", primaryjoin=id==media_group_groups.c.groupA_id, secondaryjoin=id==media_group_groups.c.groupB_id, backref="media_groups") Thanks! On Aug 13, 2:15 pm, Michael Bayer wrote: > On Aug 12, 2010, at 1:08 PM, Alvaro Reinoso wrote: > > > > > Hello, > > > I'm trying to link one table to itself. I have media groups which can > > contain more media group. I created a relation many to many: > > > media_group_groups = Table( > > "media_group_groups", > > metadata, > > Column("groupA_id", Integer, > > ForeignKey("media_groups.id")), > > Column("groupB_id", Integer, > > ForeignKey("media_groups.id")) > > ) > > > class MediaGroup(rdb.Model): > > """Represents MediaGroup class. Conteins channels and other media > > groups""" > > rdb.metadata(metadata) > > rdb.tablename("media_groups") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > parents = Column("parents", String(512)) > > > channels = relationship(Channel, secondary=media_group_channels, > > order_by=Channel.titleView, backref="media_groups") > > mediaGroup = relationship("MediaGroup", > > secondary=media_group_groups, order_by="MediaGroup.title", > > backref="media_groups") > > > I got this error: > > > "ArgumentError: Could not determine join condition between parent/ > > child tables on relationship MediaGroup.mediaGroup. Specify a > > 'primaryjoin' expression. If this is a many-to-many relationship, > > 'secondaryjoin' is needed as well." > > > When I create the tables I don't get any error, it's just when I add > > any element to it. > > Any idea??? > > > Thanks in advance! > > because you're having a particularly large amount of difficulty here, I'd > very much like to determine what about the documentation or behavior of > relationships is continuously leading you down the wrong path - this becuase > I myself am not familiar with that many ways to get an error without > eventually hitting upon the right solution. Ive taken the effort to > reconstruct every table and relationship you've expressed in this thread. > Below you will see an example of everything you've expressed, pretty much > using code snippets you've already illustrated plus reconstructions, leading > into a persistence scenario that inserts into all seven tables. I did not > come across any of the issues you describe except the initial one expressing > that primary/secondaryjoin is needed for MediaGroup.mediaGroup. > > Please start by running it as is, against the given sqlite database, so you > can see how it works. Then, I need you to determine what about your setup > is different than this, which would pinpoint the source of the issue- you do > this by blending the code below with your app, changing one part at a time > until the difference between emitting the error and working properly is > localized. Then, I need to know how to detect the mistake you've been > making and to raise a more informative error message. The "foreign_keys" > argument is virtually never needed and at the very least I think I am going > to remove the mention of that argument from the message. Let me know what > you come up with. > > from sqlalchemy import * > > from sqlalchemy.ext.declarative import declarative_base > from sqlalchemy.orm import * > > Base = declarative_base() > metadata = Base.metadata > > media_group_groups = Table( > "media_group_groups", > metadata, > Column("groupA_id", Integer, ForeignKey("media_groups.id")), > Column("groupB_id", Integer, ForeignKey("media_groups.id")) > ) > > user_media_groups = Table( > "user_media_groups", > metadata, > Column("user_id", Integer, ForeignKey("users.id")), > Column("media_group_id", Integer, ForeignKey("media_groups.id&quo
[sqlalchemy] Re: How to link one table to itself?
I've tried many things and I always get similar errors. I'm sure all the foreign keys are OK. "Could not determine relationship direction for primaryjoin condition 'users.id = user_channels.user_id', on relationship User.channels. Do the columns in 'foreign_keys' represent only the 'foreign' columns in this join condition ?". This error came up from another table and all the tables are working properly without this relation. Almost all the tables are related to each other. Maybe, this relation affects the rest of them in some way. Any idea of How I can solve this problem? Thanks! On Aug 12, 8:36 pm, Michael Bayer wrote: > On Aug 12, 2010, at 5:43 PM, Alvaro Reinoso wrote: > > > > > I'm trying that, but I got different error: > > > "Could not determine relationship direction for primaryjoin condition > > 'users.id = :id_1', on relationship User.mediaGroups. Specify the > > 'foreign_keys' argument to indicate which columns on the relationship > > are foreign." > > > As I can see, the error is related to the users table which I don't > > use in this class. However, user table is related to media_groups. > > This is the user's table: > > > class User(rdb.Model): > > """Represents the user""" > > rdb.metadata(metadata) > > rdb.tablename("users") > > > id = Column("id", Integer, primary_key=True) > > name = Column("name", String(50)) > > email = Column("email", String(50)) > > > channels = relationship(Channel, secondary=user_channels, > > order_by=Channel.titleView, backref="users") > > mediaGroups = relationship(MediaGroup, secondary=user_media_groups, > > order_by=MediaGroup.title, backref="users") > > > Do I need to add something else to that table? > > user_media_groups needs to have a ForeignKey that points to "users". > > > > > Thanks!!! > > > On Aug 12, 5:15 pm, Michael Bayer wrote: > >> On Aug 12, 2010, at 5:09 PM, Michael Bayer wrote: > > >>> On Aug 12, 2010, at 4:58 PM, Alvaro Reinoso wrote: > > >>>> I'm still working on the solution. I've found out some stuff in > >>>> internet. I guess I'm close to, but I haven't got it yet. I'm using > >>>> this for the relation: > > >>>> mediaGroups = relationship("MediaGroup", > >>>> secondary=media_group_groups, order_by="MediaGroup.title", > >>>> backref='media_groups', foreign_keys = > >>>> ["media_group_groups.groupA_id", "media_group_groups.groupB_id"], > >>>> primaryjoin = "MediaGroup.id == > >>>> media_group_groups.groupA_id", > >>>> secondaryjoin = "MediaGroup.id == media_group_groups.groupB_id") > > >>>> I'm playing with the parameters, but I usually get this error: > > >>>> "ArgumentError: Could not determine relationship direction for > >>>> primaryjoin condition 'users.id = :id_1', on relationship > >>>> User.mediaGroups. Specify the 'foreign_keys' argument to indicate > >>>> which columns on the relationship are foreign." > > >>> "media_group_groups" is not available when "primaryjoin" is evaluated as > >>> a string, nor within "foreign_keys" which is not necessary here since > >>> your meta_group_groups already has ForeignKey objects on it, so use a > >>> non-string format for primaryjoin. i will add additional examples to > >>> the declarative docs. > > >> scratch part of that, tablenames are available in the string eval as long > >> as they're from the same MetaData: > > >> mediaGroup = relationship("MediaGroup", > > >> secondary=media_group_groups, order_by="MediaGroup.title", > >> backref="media_groups", > >> primaryjoin="MediaGroup.id==media_group_groups.c.groupA_id", > >> secondaryjoin="MediaGroup.id==media_group_groups.c.groupB_id" > > >> also the error for the exampe you have above should be "'Table' object has > >> no attribute 'groupA_id'". > > >>>> Thank you! > > >>>> On Aug 12, 1:08 pm, Alvaro Reinoso wrote: > >>>>> Hello, > > >>>>> I'm trying
[sqlalchemy] Re: How to link one table to itself?
I'm trying that, but I got different error: "Could not determine relationship direction for primaryjoin condition 'users.id = :id_1', on relationship User.mediaGroups. Specify the 'foreign_keys' argument to indicate which columns on the relationship are foreign." As I can see, the error is related to the users table which I don't use in this class. However, user table is related to media_groups. This is the user's table: class User(rdb.Model): """Represents the user""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) email = Column("email", String(50)) channels = relationship(Channel, secondary=user_channels, order_by=Channel.titleView, backref="users") mediaGroups = relationship(MediaGroup, secondary=user_media_groups, order_by=MediaGroup.title, backref="users") Do I need to add something else to that table? Thanks!!! On Aug 12, 5:15 pm, Michael Bayer wrote: > On Aug 12, 2010, at 5:09 PM, Michael Bayer wrote: > > > > > > > On Aug 12, 2010, at 4:58 PM, Alvaro Reinoso wrote: > > >> I'm still working on the solution. I've found out some stuff in > >> internet. I guess I'm close to, but I haven't got it yet. I'm using > >> this for the relation: > > >> mediaGroups = relationship("MediaGroup", > >> secondary=media_group_groups, order_by="MediaGroup.title", > >> backref='media_groups', foreign_keys = > >> ["media_group_groups.groupA_id", "media_group_groups.groupB_id"], > >> primaryjoin = "MediaGroup.id == > >> media_group_groups.groupA_id", > >> secondaryjoin = "MediaGroup.id == media_group_groups.groupB_id") > > >> I'm playing with the parameters, but I usually get this error: > > >> "ArgumentError: Could not determine relationship direction for > >> primaryjoin condition 'users.id = :id_1', on relationship > >> User.mediaGroups. Specify the 'foreign_keys' argument to indicate > >> which columns on the relationship are foreign." > > > "media_group_groups" is not available when "primaryjoin" is evaluated as a > > string, nor within "foreign_keys" which is not necessary here since your > > meta_group_groups already has ForeignKey objects on it, so use a non-string > > format for primaryjoin. i will add additional examples to the declarative > > docs. > > scratch part of that, tablenames are available in the string eval as long as > they're from the same MetaData: > > mediaGroup = relationship("MediaGroup", > > secondary=media_group_groups, order_by="MediaGroup.title", > backref="media_groups", > primaryjoin="MediaGroup.id==media_group_groups.c.groupA_id", > secondaryjoin="MediaGroup.id==media_group_groups.c.groupB_id" > > also the error for the exampe you have above should be "'Table' object has no > attribute 'groupA_id'". > > > > >> Thank you! > > >> On Aug 12, 1:08 pm, Alvaro Reinoso wrote: > >>> Hello, > > >>> I'm trying to link one table to itself. I have media groups which can > >>> contain more media group. I created a relation many to many: > > >>> media_group_groups = Table( > >>> "media_group_groups", > >>> metadata, > >>> Column("groupA_id", Integer, > >>> ForeignKey("media_groups.id")), > >>> Column("groupB_id", Integer, > >>> ForeignKey("media_groups.id")) > >>> ) > > >>> class MediaGroup(rdb.Model): > >>> """Represents MediaGroup class. Conteins channels and other media > >>> groups""" > >>> rdb.metadata(metadata) > >>> rdb.tablename("media_groups") > > >>> id = Column("id", Integer, primary_key=True) > >>> title = Column("title", String(100)) > >>> parents = Column("parents", String(512)) > > >>> channels = relationship(Channel, secondary=media_group_channels, > >>> order_by=Channel.titleView, backre
[sqlalchemy] Re: How to link one table to itself?
I'm still working on the solution. I've found out some stuff in internet. I guess I'm close to, but I haven't got it yet. I'm using this for the relation: mediaGroups = relationship("MediaGroup", secondary=media_group_groups, order_by="MediaGroup.title", backref='media_groups', foreign_keys = ["media_group_groups.groupA_id", "media_group_groups.groupB_id"], primaryjoin = "MediaGroup.id == media_group_groups.groupA_id", secondaryjoin = "MediaGroup.id == media_group_groups.groupB_id") I'm playing with the parameters, but I usually get this error: "ArgumentError: Could not determine relationship direction for primaryjoin condition 'users.id = :id_1', on relationship User.mediaGroups. Specify the 'foreign_keys' argument to indicate which columns on the relationship are foreign." Thank you! On Aug 12, 1:08 pm, Alvaro Reinoso wrote: > Hello, > > I'm trying to link one table to itself. I have media groups which can > contain more media group. I created a relation many to many: > > media_group_groups = Table( > "media_group_groups", > metadata, > Column("groupA_id", Integer, > ForeignKey("media_groups.id")), > Column("groupB_id", Integer, > ForeignKey("media_groups.id")) > ) > > class MediaGroup(rdb.Model): > """Represents MediaGroup class. Conteins channels and other media > groups""" > rdb.metadata(metadata) > rdb.tablename("media_groups") > > id = Column("id", Integer, primary_key=True) > title = Column("title", String(100)) > parents = Column("parents", String(512)) > > channels = relationship(Channel, secondary=media_group_channels, > order_by=Channel.titleView, backref="media_groups") > mediaGroup = relationship("MediaGroup", > secondary=media_group_groups, order_by="MediaGroup.title", > backref="media_groups") > > I got this error: > > "ArgumentError: Could not determine join condition between parent/ > child tables on relationship MediaGroup.mediaGroup. Specify a > 'primaryjoin' expression. If this is a many-to-many relationship, > 'secondaryjoin' is needed as well." > > When I create the tables I don't get any error, it's just when I add > any element to it. > Any idea??? > > Thanks in advance! -- 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.
[sqlalchemy] How to link one table to itself?
Hello, I'm trying to link one table to itself. I have media groups which can contain more media group. I created a relation many to many: media_group_groups = Table( "media_group_groups", metadata, Column("groupA_id", Integer, ForeignKey("media_groups.id")), Column("groupB_id", Integer, ForeignKey("media_groups.id")) ) class MediaGroup(rdb.Model): """Represents MediaGroup class. Conteins channels and other media groups""" rdb.metadata(metadata) rdb.tablename("media_groups") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) parents = Column("parents", String(512)) channels = relationship(Channel, secondary=media_group_channels, order_by=Channel.titleView, backref="media_groups") mediaGroup = relationship("MediaGroup", secondary=media_group_groups, order_by="MediaGroup.title", backref="media_groups") I got this error: "ArgumentError: Could not determine join condition between parent/ child tables on relationship MediaGroup.mediaGroup. Specify a 'primaryjoin' expression. If this is a many-to-many relationship, 'secondaryjoin' is needed as well." When I create the tables I don't get any error, it's just when I add any element to it. Any idea??? Thanks in advance! -- 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.
[sqlalchemy] To select a few columns in some tables related
Hello, I have these classes: class Channel(rdb.Model): rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) items = relationship("MediaItem", secondary=channel_items, order_by="MediaItem.titleView", backref="channels") class MediaItem(rdb.Model): rdb.metadata(metadata) rdb.tablename("media_items") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) class User(rdb.Model): rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) channels = relationship("Channel", secondary=user_channels, order_by="Channel.titleView", backref="users") MediaItem is related to Channel and Channel is related to User. if I'd like to select some columns from items and channels, I'd do this: session = Session() result = session.query(Channel).join(Channel.items).values(Channel.title, Item.title) I get an instance of Channel class with its items. My problem is I don't know how to select some columns from User, Channel and Item. How can I make a query where for example, I can select the User.name property and its channels with only Channel.title property and the items of those channels with only Item.title property? Thanks in advance! -- 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.
[sqlalchemy] Re: Problems with the relation one to many
Solved it. I'm using grok as CMS and didn't realize I have to "grok" every component every time when I use it. That's why I got that error. Thanks anyway! On Aug 4, 4:27 pm, Alvaro Reinoso wrote: > Hello, > > I got this error when I've tried to relate some classes: > > "UnmappedClassError: Class 'zeppelinlib.user.UserTest.User' is not > mapped" > > I don't get errors when I have relation many-to-many. > > This is my file where I store all the User classes. > > user_channels = Table( > "user_channels", > metadata, > Column("user_id", Integer, ForeignKey("users.id")), > Column("channel_id", Integer, ForeignKey(Channel.id)) > ) > > group_permissions = Table( > "group_permissions", > metadata, > Column("group_id", Integer, > ForeignKey("user_groups.id")), > Column("permission_id", Integer, > ForeignKey(Permission.id)) > ) > > class User(rdb.Model): > """Represents the user""" > rdb.metadata(metadata) > rdb.tablename("users") > > id = Column("id", Integer, primary_key=True) > name = Column("name", String(50)) > email = Column("email", String(50)) > group_id = Column("group_id", Integer, ForeignKey("user_groups.id")) > > channels = relation(Channel, secondary=user_channels, > backref="channels") > > class UserGroup(rdb.Model): > """Represents a group of users with the same features""" > rdb.metadata(metadata) > rdb.tablename("user_groups") > > id = Column("id", Integer, primary_key=True) > title = Column("title", String(50)) > > users = relation(User, backref="users") > permissions = relation(Permission, secondary=group_permissions, > backref="permissions") > > How can I solve it? > > Thanks in advance! -- 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.
[sqlalchemy] Problems with the relation one to many
Hello, I got this error when I've tried to relate some classes: "UnmappedClassError: Class 'zeppelinlib.user.UserTest.User' is not mapped" I don't get errors when I have relation many-to-many. This is my file where I store all the User classes. user_channels = Table( "user_channels", metadata, Column("user_id", Integer, ForeignKey("users.id")), Column("channel_id", Integer, ForeignKey(Channel.id)) ) group_permissions = Table( "group_permissions", metadata, Column("group_id", Integer, ForeignKey("user_groups.id")), Column("permission_id", Integer, ForeignKey(Permission.id)) ) class User(rdb.Model): """Represents the user""" rdb.metadata(metadata) rdb.tablename("users") id = Column("id", Integer, primary_key=True) name = Column("name", String(50)) email = Column("email", String(50)) group_id = Column("group_id", Integer, ForeignKey("user_groups.id")) channels = relation(Channel, secondary=user_channels, backref="channels") class UserGroup(rdb.Model): """Represents a group of users with the same features""" rdb.metadata(metadata) rdb.tablename("user_groups") id = Column("id", Integer, primary_key=True) title = Column("title", String(50)) users = relation(User, backref="users") permissions = relation(Permission, secondary=group_permissions, backref="permissions") How can I solve it? Thanks in advance! -- 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.
[sqlalchemy] Re: To select only some columns from some tables using session object, relation many-to-many
It works out, thank you! How could I just retrieve some columns from both tables? For example, if I try to select some columns from Item and Channel, I get "" when I'd like to get a channel type with its items: result = session.query(Channel.title, Item.title).join('items').filter(Item.typeItem == "zeppelin/ channel").order_by(Channel.titleView).all() I just need some values many times, I don't need to retrieve the whole object. Thanks in advance! On Aug 3, 1:40 am, Kalium wrote: > On Aug 3, 8:43 am, Alvaro Reinoso wrote: > > > > > Hello, > > > I have these classes where items (class Item) is related to channel > > object. Channel can contain many items: > > > channel_items = Table( > > "channel_items", > > metadata, > > Column("channel_id", Integer, > > ForeignKey("channels.id")), > > Column("item_id", Integer, > > ForeignKey(Item.id)) > > ) > > > class Channel(rdb.Model): > > rdb.metadata(metadata) > > rdb.tablename("channels") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > > items = relation(Item, secondary=channel_items, > > backref="channels") > > > class Item(rdb.Model): > > rdb.metadata(metadata) > > rdb.tablename("items") > > > id = Column("id", Integer, primary_key=True) > > title = Column("title", String(100)) > > > I know how to get all the columns using something like: > > > session = rdb.Session() channels = > > session.query(Channel).order_by(Channel.title) > > > However, I'd like to select some columns from both tables with some > > conditions in Item. For example, select all the channels where > > item.type = 'jpg'. I'd like to get a channel object with items > > attributes with that condition for example. How can I do that? > > > I've tried something like (no one worked out): > > > result = session.query(Channel).filter(Item.typeItem != 'zeppelin/ > > channel').all() > > result = session.query(Channel, Item).filter(Item.typeItem != > > 'zeppelin/channel').all() > > > Thanks in advance! > > Try something like > > session.query(Channel).join('items').filter(Item.typeItem != > 'whatever').all() -- 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.
[sqlalchemy] To select only some columns from some tables using session object, relation many-to-many
Hello, I have these classes where items (class Item) is related to channel object. Channel can contain many items: channel_items = Table( "channel_items", metadata, Column("channel_id", Integer, ForeignKey("channels.id")), Column("item_id", Integer, ForeignKey(Item.id)) ) class Channel(rdb.Model): rdb.metadata(metadata) rdb.tablename("channels") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) items = relation(Item, secondary=channel_items, backref="channels") class Item(rdb.Model): rdb.metadata(metadata) rdb.tablename("items") id = Column("id", Integer, primary_key=True) title = Column("title", String(100)) I know how to get all the columns using something like: session = rdb.Session() channels = session.query(Channel).order_by(Channel.title) However, I'd like to select some columns from both tables with some conditions in Item. For example, select all the channels where item.type = 'jpg'. I'd like to get a channel object with items attributes with that condition for example. How can I do that? I've tried something like (no one worked out): result = session.query(Channel).filter(Item.typeItem != 'zeppelin/ channel').all() result = session.query(Channel, Item).filter(Item.typeItem != 'zeppelin/channel').all() Thanks in advance! -- 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.