[sqlalchemy] Re: relationships for no-table-related Class

2010-11-16 Thread neurino
I didn't mean mapping Root to a Table (if not necessary) is my intent,
what I'd like to know is how to get the same behavior without the
bloat of an extra table.

 make your application work a certain way (where certain way here is not 
 clear)

I make an example, maybe I'm wrong tho:

let's say I delete an item, I'd expect not to find this item anymore
in its (ex) parent items

subarea.items
[item]
session.delete(subarea.items[0])
session.commit()
subarea.items
[]

This would be not the same for root's areas if I just use a query

root.areas = query(Area).all()
root.areas
[area]
session.delete(root.areas[0])
session.commit()
root.items
[area]

I hope I has been able to focus on my question now.

Thanks for your help
neurino

On Nov 15, 9:57 pm, Michael Bayer mike...@zzzcomputing.com wrote:
 On Nov 15, 2010, at 10:46 AM, neurino wrote:

  Thanks for your answer first.

  Root is a singleton, its class is not mapped to a table.

  What I mean is I could add a table roots to the database with a
  sigle row and add areas a foreign key root_id and create a
  relationship as from subareas with parent area and get what I'm
  talking about.

 sure, then you're mapping Root to a table, and having just one row.   That 
 would make Root.area act exactly like a relationship() though its a little 
 strange to have a row in the database just to make your application work a 
 certain way (where certain way here is not clear).





  This relationship, between root and area, as long as areas and
  subareas would come in handy for example to traverse the tree for
  extracting an xml simply, or to make recursive calculations.

  Before sqlalchemy I was used to add all areas, subareas, items, parent
  attributes to classes by myself but now I'm in the situation that 80%
  of the work is done by sqlalchemy automatically and I'm not sure how
  to fill the remaining, possibly having both areas and subareas behave
  at the same way to avoid confusion (just as an example, lazy loading).

  Thanks for your support
  neurino

  On Nov 15, 3:49 pm, Michael Bayer mike...@zzzcomputing.com wrote:
  On Nov 15, 2010, at 8:06 AM, neurino wrote:

  So no advice?

  Are relationships and backref something more than attributes I can
  setup with a query?

  Thank you for your support.

  what's not stated clearly here is what Root is.  If that's not a class 
  mapped to a table, then you'd just need to use regular Python attributes 
  and descriptors to establish the in-python behavior you're looking for.  
  Seems like its essentially some kind of query object, so your 
  query.all()/.parent = some_root approach is what you'd go with, though it 
  would appear that Root is a singleton anyway, meaning this could be 
  established on Area at the class level instead of assigning to each 
  instance.

  Its not clear what other behavior of relationship() would apply here, 
  since Root has no database identity.

  On Nov 11, 9:45 am, neurino neur...@gmail.com wrote:
  I have a tree structure

  Root
    |
    +--Area
    |    |
    |    +--SubArea
    |    |    |
    |    |    +--Item
    |    |    |
    |    |    +--Item
    |    |
    |    +--SubArea
    |         |
    |         +--Item
    |         |
    |         +--Item
    |
    +--Area
         |
         +--SubArea
         |    |
         |    +--Item
         |    |
         |    +--Item
         |
         +--SubArea
              |
              +--Item
              |
              +--Item

  The tree structure corresponds to slqalchemy db tables `areas`,
  `subareas` and `items`.

  Something like this:

      mapper(Area, areas_table, properties={
          'subareas': relationship(SubArea, backref='parent'),
          })
      mapper(SubArea, subareas__table, properties={
          'items': relationship(Item, backref='parent'),
          })
      mapper(Item, items_table)

  so each Area instance will have a `subareas` list and each SubArea
  will have a `items` list,

  also I easyly get a backref `parent` from Item to parent SubArea and
  from
  SubArea to parent Area.

  But this won't be for Root: it will not have a `areas` list in Root
  nor its areas will have a parent reference to Root.

  The quick-and-dirty solution is to do this in Root:

      self.areas = query(Area).all()
      for area in self.areas:
          area.parent = self

  But it won't be the same thing as sqlalchemy `relationship` attributes
  so:
  are there alternative solutions more sqlalchemy-like?

  Any tip appreciated!

  Thank you for your support

  Greetings
  neurino

  --
  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 

[sqlalchemy] Re: version_id_col and custom DeclarativeMeta with 0.6

2010-11-16 Thread Joril
On 15 Nov, 18:57, Michael Bayer mike...@zzzcomputing.com wrote:

 First off, I can't reproduce your issue:

Found the culprit: I had a stray 0.5.8 directory lying around, and of
course it was being picked up.. T_T Sorry :(

 Second, if you want to switch to newer declarative features, just stick your 
 __mapper_args__ on Base:

 class Base(object):
     version = Column(Integer)

     @declared_attr
     def __mapper_args__(cls):
         return {'version_id_col':cls.version}

 Base = declarative_base(cls=Base)

Very nice! 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.



Re: [sqlalchemy] order_by: ArgumentError

2010-11-16 Thread Enrico Morelli
On Mon, 15 Nov 2010 15:56:06 -0500
Michael Bayer mike...@zzzcomputing.com wrote:

 its looking for a Column object.menus_table.c.weight instead of
 'weight'.
 

Thanks, I modified the query:
main_menu = Session.query(Menu).filter(and_(Menu.parent_id==None,
Menu.lang==session['lang'])).order_by(menus_table.c.weight.asc()).all()

 but the error is the same:

ArgumentError: Column-based expression object expected for argument
'order_by'; got: 'weight', type type 'str'

 
 On Nov 15, 2010, at 10:03 AM, Enrico Morelli wrote:
 
  Dear all,
  
  I've a lot of applications using SA 0.5.6. Now I upgraded my
  personal computer and now I can use SA 0.6.5 but my applications
  stops to work.
  
  I receive the error:
  ArgumentError: Column-based expression object expected for argument
  'order_by'; got: 'weight', type type 'str'
  
  I try to search in google but I don't understand why I receive this
  error. Someone can explain to me?
  
  Thanks in advance
  
  This is the table declaration:
  
  menus_table = Table('menus', metadata,
 Column('id', types.Integer, primary_key=True),
 Column('parent_id', types.Integer, ForeignKey('menus.id')),
 Column('name', types.Unicode(80), nullable=False),
 Column('title', types.Unicode(80)),
 Column('url', types.Unicode(80)),
 Column('weight', types.Integer, index=True),
 Column('lang', types.Unicode(2))
  )
  
  This is the mapper declaration:
  mapper(Menu, menus_table,
properties={
'children': relation(Menu, order_by='weight'),
'permissions': relation(Permissions, backref='menus',
secondary=menus_permissions_table)
})
  
  At the end the query:
  main_menu = Session.query(Menu).filter(and_(Menu.parent_id==None,
  Menu.lang==session['lang'])).order_by(Menu.weight.asc()).all()
  
  -- 
  ---
(o_
  (o_//\  Coltivate Linux che tanto Windows si pianta da solo.
  (/)_   V_/_
  +--+
  | ENRICO MORELLI |  email: more...@cerm.unifi.it   |
  | * *   *   *|  phone: +39 055 4574269 |
  |  University of Florence|  fax  : +39 055 4574253 |
  |  CERM - via Sacconi, 6 -  50019 Sesto Fiorentino (FI) - ITALY|
  +--+
  
  -- 
  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.
  
 


-- 
---
   (o_
(o_//\  Coltivate Linux che tanto Windows si pianta da solo.
(/)_   V_/_
+--+
| ENRICO MORELLI |  email: more...@cerm.unifi.it   |
| * *   *   *|  phone: +39 055 4574269 |
|  University of Florence|  fax  : +39 055 4574253 |
|  CERM - via Sacconi, 6 -  50019 Sesto Fiorentino (FI) - ITALY|
+--+

-- 
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] association_proxy as property?

2010-11-16 Thread A . M .
Hello,

To generate json from our SQLAlchemy model objects, we are using 
iterate_properties to determine how to dictify the object. One of our objects 
uses association_proxy which we would like to represent in the JSON. 
Unfortunately, because it is not a property, the dictification misses this 
property. I feel like I am missing something simple here.

How can I make an association_proxy appear to be a property which appears in 
iterate_properties of the mapper?

Cheers,
M


-- 
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.



Re: [sqlalchemy] order_by: ArgumentError

2010-11-16 Thread Michael Bayer

On Nov 16, 2010, at 6:16 AM, Enrico Morelli wrote:

 On Mon, 15 Nov 2010 15:56:06 -0500
 Michael Bayer mike...@zzzcomputing.com wrote:
 
 its looking for a Column object.menus_table.c.weight instead of
 'weight'.
 
 
 Thanks, I modified the query:
 main_menu = Session.query(Menu).filter(and_(Menu.parent_id==None,
 Menu.lang==session['lang'])).order_by(menus_table.c.weight.asc()).all()
 
 but the error is the same:
 
 ArgumentError: Column-based expression object expected for argument
 'order_by'; got: 'weight', type type 'str'

no , the mapping:

mapper(Menu, menus_table,
 properties={
 'children': relation(Menu, order_by=menus_table.c.weight),
 'permissions': relation(Permissions, backref='menus',
 secondary=menus_permissions_table)
 })


 
 
 On Nov 15, 2010, at 10:03 AM, Enrico Morelli wrote:
 
 Dear all,
 
 I've a lot of applications using SA 0.5.6. Now I upgraded my
 personal computer and now I can use SA 0.6.5 but my applications
 stops to work.
 
 I receive the error:
 ArgumentError: Column-based expression object expected for argument
 'order_by'; got: 'weight', type type 'str'
 
 I try to search in google but I don't understand why I receive this
 error. Someone can explain to me?
 
 Thanks in advance
 
 This is the table declaration:
 
 menus_table = Table('menus', metadata,
   Column('id', types.Integer, primary_key=True),
   Column('parent_id', types.Integer, ForeignKey('menus.id')),
   Column('name', types.Unicode(80), nullable=False),
   Column('title', types.Unicode(80)),
   Column('url', types.Unicode(80)),
   Column('weight', types.Integer, index=True),
   Column('lang', types.Unicode(2))
 )
 
 This is the mapper declaration:
 mapper(Menu, menus_table,
  properties={
  'children': relation(Menu, order_by='weight'),
  'permissions': relation(Permissions, backref='menus',
  secondary=menus_permissions_table)
  })
 
 At the end the query:
 main_menu = Session.query(Menu).filter(and_(Menu.parent_id==None,
 Menu.lang==session['lang'])).order_by(Menu.weight.asc()).all()
 
 -- 
 ---
  (o_
 (o_//\  Coltivate Linux che tanto Windows si pianta da solo.
 (/)_   V_/_
 +--+
 | ENRICO MORELLI |  email: more...@cerm.unifi.it   |
 | * *   *   *|  phone: +39 055 4574269 |
 |  University of Florence|  fax  : +39 055 4574253 |
 |  CERM - via Sacconi, 6 -  50019 Sesto Fiorentino (FI) - ITALY|
 +--+
 
 -- 
 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.
 
 
 
 
 -- 
 ---
   (o_
 (o_//\  Coltivate Linux che tanto Windows si pianta da solo.
 (/)_   V_/_
 +--+
 | ENRICO MORELLI |  email: more...@cerm.unifi.it   |
 | * *   *   *|  phone: +39 055 4574269 |
 |  University of Florence|  fax  : +39 055 4574253 |
 |  CERM - via Sacconi, 6 -  50019 Sesto Fiorentino (FI) - ITALY|
 +--+
 
 -- 
 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.
 

-- 
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.



Re: [sqlalchemy] association_proxy as property?

2010-11-16 Thread Michael Bayer

On Nov 16, 2010, at 11:14 AM, A.M. wrote:

 Hello,
 
 To generate json from our SQLAlchemy model objects, we are using 
 iterate_properties to determine how to dictify the object. One of our 
 objects uses association_proxy which we would like to represent in the JSON. 
 Unfortunately, because it is not a property, the dictification misses this 
 property. I feel like I am missing something simple here.
 
 How can I make an association_proxy appear to be a property which appears in 
 iterate_properties of the mapper?

1. why not use dir(myobject) to get a view of your object as a whole ?
2. implicit conversion to JSON and such is a little sloppy.   You'd be better 
off using a structured approach like Colander: http://docs.repoze.org/colander/


-- 
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.



Re: [sqlalchemy] Re: relationships for no-table-related Class

2010-11-16 Thread Michael Bayer

On Nov 16, 2010, at 4:19 AM, neurino wrote:

 I didn't mean mapping Root to a Table (if not necessary) is my intent,
 what I'd like to know is how to get the same behavior without the
 bloat of an extra table.
 
 make your application work a certain way (where certain way here is not 
 clear)
 
 I make an example, maybe I'm wrong tho:
 
 let's say I delete an item, I'd expect not to find this item anymore
 in its (ex) parent items
 
 subarea.items
 [item]
 session.delete(subarea.items[0])
 session.commit()
 subarea.items
 []
 
 This would be not the same for root's areas if I just use a query
 
 root.areas = query(Area).all()
 root.areas
 [area]
 session.delete(root.areas[0])
 session.commit()
 root.items
 [area]
 
 I hope I has been able to focus on my question now.


right so I'd just make the attribute live:

Session = scoped_session(sessionmaker())

class Root(object):
   @property
   def areas(self):
return Session.query(Area).all()

singleton_root = Root()

class Area(object):
   parent = singleton_root


This is no different than the example above - 
Session.delete(someobject.collection[someindex]) does not remove the item from 
the collection - its only because of the call to commit() that 
someobject.collection is expired, and is then reloaded.

If you'd like to later add caching to Root.areas such that the collection is 
pulled from memory until Session.commit() is called, you could enhance 
Root.areas to maintain values in a cache, such as a WeakKeyDictionary which 
uses Session().transaction as the key.












 
 Thanks for your help
 neurino
 
 On Nov 15, 9:57 pm, Michael Bayer mike...@zzzcomputing.com wrote:
 On Nov 15, 2010, at 10:46 AM, neurino wrote:
 
 Thanks for your answer first.
 
 Root is a singleton, its class is not mapped to a table.
 
 What I mean is I could add a table roots to the database with a
 sigle row and add areas a foreign key root_id and create a
 relationship as from subareas with parent area and get what I'm
 talking about.
 
 sure, then you're mapping Root to a table, and having just one row.   That 
 would make Root.area act exactly like a relationship() though its a little 
 strange to have a row in the database just to make your application work a 
 certain way (where certain way here is not clear).
 
 
 
 
 
 This relationship, between root and area, as long as areas and
 subareas would come in handy for example to traverse the tree for
 extracting an xml simply, or to make recursive calculations.
 
 Before sqlalchemy I was used to add all areas, subareas, items, parent
 attributes to classes by myself but now I'm in the situation that 80%
 of the work is done by sqlalchemy automatically and I'm not sure how
 to fill the remaining, possibly having both areas and subareas behave
 at the same way to avoid confusion (just as an example, lazy loading).
 
 Thanks for your support
 neurino
 
 On Nov 15, 3:49 pm, Michael Bayer mike...@zzzcomputing.com wrote:
 On Nov 15, 2010, at 8:06 AM, neurino wrote:
 
 So no advice?
 
 Are relationships and backref something more than attributes I can
 setup with a query?
 
 Thank you for your support.
 
 what's not stated clearly here is what Root is.  If that's not a class 
 mapped to a table, then you'd just need to use regular Python attributes 
 and descriptors to establish the in-python behavior you're looking for.  
 Seems like its essentially some kind of query object, so your 
 query.all()/.parent = some_root approach is what you'd go with, though it 
 would appear that Root is a singleton anyway, meaning this could be 
 established on Area at the class level instead of assigning to each 
 instance.
 
 Its not clear what other behavior of relationship() would apply here, 
 since Root has no database identity.
 
 On Nov 11, 9:45 am, neurino neur...@gmail.com wrote:
 I have a tree structure
 
 Root
   |
   +--Area
   ||
   |+--SubArea
   |||
   ||+--Item
   |||
   ||+--Item
   ||
   |+--SubArea
   | |
   | +--Item
   | |
   | +--Item
   |
   +--Area
|
+--SubArea
||
|+--Item
||
|+--Item
|
+--SubArea
 |
 +--Item
 |
 +--Item
 
 The tree structure corresponds to slqalchemy db tables `areas`,
 `subareas` and `items`.
 
 Something like this:
 
 mapper(Area, areas_table, properties={
 'subareas': relationship(SubArea, backref='parent'),
 })
 mapper(SubArea, subareas__table, properties={
 'items': relationship(Item, backref='parent'),
 })
 mapper(Item, items_table)
 
 so each Area instance will have a `subareas` list and each SubArea
 will have a `items` list,
 
 also I easyly get a backref `parent` from Item to parent SubArea and
 from
 SubArea to parent Area.
 
 But this won't be for Root: it will not have a `areas` list in Root
 nor its areas will have a parent 

Re: [sqlalchemy] association_proxy as property?

2010-11-16 Thread A.M.

On Nov 16, 2010, at 11:43 AM, Michael Bayer wrote:

 
 On Nov 16, 2010, at 11:14 AM, A.M. wrote:
 
 Hello,
 
 To generate json from our SQLAlchemy model objects, we are using 
 iterate_properties to determine how to dictify the object. One of our 
 objects uses association_proxy which we would like to represent in the JSON. 
 Unfortunately, because it is not a property, the dictification misses this 
 property. I feel like I am missing something simple here.
 
 How can I make an association_proxy appear to be a property which appears in 
 iterate_properties of the mapper?
 
 1. why not use dir(myobject) to get a view of your object as a whole ?

We swiped dictify from sprox.saormprovider:
http://bitbucket.org/percious/sprox/src/tip/sprox/saormprovider.py#cl-321

We like the behavior that a REST call to retrieve an SQLAlchemy object returns 
pks for relationships (instead of loading the entire result hierarchy), so 
subsequent REST calls are required to dig deeper into the tree of results.

Using dir() is definitely a good suggestion which I will try. You are probably 
right that we are using iterate_properties improperly.

 2. implicit conversion to JSON and such is a little sloppy.   You'd be better 
 off using a structured approach like Colander: 
 http://docs.repoze.org/colander/

It looks like I would have to either re-define all objects using the Colander 
syntax or implement a method which converts existing SQLAlchemy models to 
Colander schema objects. Even if the latter function already exists, I still 
have the problem of determining automatically which properties to encode, no?

Cheers,
M

-- 
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.



Re: [sqlalchemy] association_proxy as property?

2010-11-16 Thread jason kirtland
On Tue, Nov 16, 2010 at 9:05 AM, A.M. age...@themactionfaction.com wrote:

 On Nov 16, 2010, at 11:43 AM, Michael Bayer wrote:


 On Nov 16, 2010, at 11:14 AM, A.M. wrote:
 To generate json from our SQLAlchemy model objects, we are using 
 iterate_properties to determine how to dictify the object. One of our 
 objects uses association_proxy which we would like to represent in the 
 JSON. Unfortunately, because it is not a property, the dictification misses 
 this property. I feel like I am missing something simple here.

 How can I make an association_proxy appear to be a property which appears 
 in iterate_properties of the mapper?

 2. implicit conversion to JSON and such is a little sloppy.   You'd be 
 better off using a structured approach like Colander: 
 http://docs.repoze.org/colander/

 It looks like I would have to either re-define all objects using the Colander 
 syntax or implement a method which converts existing SQLAlchemy models to 
 Colander schema objects. Even if the latter function already exists, I still 
 have the problem of determining automatically which properties to encode, no?

You may find you'll need to do even further work to determine which
properties to encode.  I do the same (using Flatland for
serialization), and part of that challenge was determining where the
edges of the business objects were.  (If you have relations, maybe
some of them are part of the object (as user's email addresses) and
some of them aren't (a User-Users list of the user's friends). In the
end I went with a combination of class annotation and heuristics based
on iterating mapper properties.  This allowed me to traverse the
mappings to reliably find the edges and also include the occasional
transient attribute or other oddball that needed to be in the
serialized form.

-- 
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.



Re: [sqlalchemy] association_proxy as property?

2010-11-16 Thread Michael Bayer

On Nov 16, 2010, at 12:05 PM, A.M. wrote:

 
 2. implicit conversion to JSON and such is a little sloppy.   You'd be 
 better off using a structured approach like Colander: 
 http://docs.repoze.org/colander/
 
 It looks like I would have to either re-define all objects using the Colander 
 syntax or implement a method which converts existing SQLAlchemy models to 
 Colander schema objects. Even if the latter function already exists, I still 
 have the problem of determining automatically which properties to encode, no?

Jek's suggestion is good here, also in my experience when I need to use JSON 
for something, it implies I'm communicating with some other system that doesn't 
know about my mapped objects - meaning, even if the JSON structure is initially 
driven by the ORM completely, I need the JSON structure to remain independent 
of changes in the ORM model in any case.   But usually I'm dealing with a 
service that looks dramatically different from my ORM models anyway.   Its 
again the same dichotomy in SQLAlchemy itself, your json messages are not your 
domain objects ;)

I haven't used Colander and instead have something homegrown - a core feature 
is that it maintains a mapping of object attributes, in some cases 
dot-separated paths, to field names that would be generated in JSON or XML.   I 
also use it to translate against .csv and .xls formats.   Most apps I work on 
end up that way, so I go straight to explicit mappings up front since I know 
the variability is going to be great.


-- 
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

2010-11-16 Thread Alvaro Reinoso
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] using __mapper_args__ with Declarative ORM

2010-11-16 Thread Royce
Using version 0.6.5 under python 2.6.5 even simple augments to
__mapper_args__ variable course errors

E.g.
from sqlalchemy import *
from sqlalchemy.dialects.mysql import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class CourseAliases(Base):
__tablename__ = 'CourseAliases'

alias= Column(CHAR(length=7), nullable=False)
year = Column(INTEGER())
course_stream_id = Column(INTEGER(), nullable=False)
auto_gen = Column(CHAR(length=1), nullable=False)

__mapper_args__ = {
'primary_key': course_stream_id
}


If I try to import it the resultant errors are

from tables import CourseAliases2
Traceback (most recent call last):
  File stdin, line 1, in module
  File tables/CourseAliases2.py, line 7, in module
class CourseAliases(Base):
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/ext/declarative.py, line 1231, in __init__
_as_declarative(cls, classname, cls.__dict__)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/ext/declarative.py, line 1224, in
_as_declarative
**mapper_args)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/orm/__init__.py, line 861, in mapper
return Mapper(class_, local_table, *args, **params)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/orm/mapper.py, line 217, in __init__
self._configure_pks()
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/orm/mapper.py, line 481, in _configure_pks
if self.primary_key_argument:
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/sql/expression.py, line 1423, in __nonzero__
raise TypeError(Boolean value of this clause is not defined)
TypeError: Boolean value of this clause is not defined

I know I can add the primary_key=True to a Column but what I actually
wanted to do is make a multiple column primary key

E.g
__mapper_args__ = {
'primary_key':  [course_stream_id,alias]
}

this produces a different error.

Traceback (most recent call last):
  File stdin, line 1, in module
  File tables/CourseAliases2.py, line 7, in module
class CourseAliases(Base):
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/ext/declarative.py, line 1231, in __init__
_as_declarative(cls, classname, cls.__dict__)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
py2.6.egg/sqlalchemy/ext/declarative.py, line 1048, in
_as_declarative
mapper_args[k] = column_copies.get(v,v)
TypeError: Error when calling the metaclass bases
unhashable type: 'list'

What am I doing wrong ? I am fairly sure I am only doing what the
documentation says.

Thanks for any help
Royce



-- 
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.



Re: [sqlalchemy] using __mapper_args__ with Declarative ORM

2010-11-16 Thread Michael Bayer
primary_key argument to mapper is a list

primary_key=[my_column, my_other_column, ..]

clearly this is a bug: http://www.sqlalchemy.org/docs/orm/mapper_config.html#, 
ill change that now


I'll see if I can add a scalar-list adapter in 0.7 for that arg


On Nov 16, 2010, at 4:53 PM, Royce wrote:

 Using version 0.6.5 under python 2.6.5 even simple augments to
 __mapper_args__ variable course errors
 
 E.g.
 from sqlalchemy import *
 from sqlalchemy.dialects.mysql import *
 from sqlalchemy.ext.declarative import declarative_base
 
 Base = declarative_base()
 
 class CourseAliases(Base):
__tablename__ = 'CourseAliases'
 
alias= Column(CHAR(length=7), nullable=False)
year = Column(INTEGER())
course_stream_id = Column(INTEGER(), nullable=False)
auto_gen = Column(CHAR(length=1), nullable=False)
 
__mapper_args__ = {
'primary_key': course_stream_id
}
 
 
 If I try to import it the resultant errors are
 
 from tables import CourseAliases2
 Traceback (most recent call last):
  File stdin, line 1, in module
  File tables/CourseAliases2.py, line 7, in module
class CourseAliases(Base):
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/ext/declarative.py, line 1231, in __init__
_as_declarative(cls, classname, cls.__dict__)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/ext/declarative.py, line 1224, in
 _as_declarative
**mapper_args)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/orm/__init__.py, line 861, in mapper
return Mapper(class_, local_table, *args, **params)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/orm/mapper.py, line 217, in __init__
self._configure_pks()
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/orm/mapper.py, line 481, in _configure_pks
if self.primary_key_argument:
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/sql/expression.py, line 1423, in __nonzero__
raise TypeError(Boolean value of this clause is not defined)
 TypeError: Boolean value of this clause is not defined
 
 I know I can add the primary_key=True to a Column but what I actually
 wanted to do is make a multiple column primary key
 
 E.g
 __mapper_args__ = {
'primary_key':  [course_stream_id,alias]
}
 
 this produces a different error.
 
 Traceback (most recent call last):
  File stdin, line 1, in module
  File tables/CourseAliases2.py, line 7, in module
class CourseAliases(Base):
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/ext/declarative.py, line 1231, in __init__
_as_declarative(cls, classname, cls.__dict__)
  File /usr/pkg/lib/python2.6/site-packages/SQLAlchemy-0.6.5-
 py2.6.egg/sqlalchemy/ext/declarative.py, line 1048, in
 _as_declarative
mapper_args[k] = column_copies.get(v,v)
 TypeError: Error when calling the metaclass bases
unhashable type: 'list'
 
 What am I doing wrong ? I am fairly sure I am only doing what the
 documentation says.
 
 Thanks for any help
 Royce
 
 
 
 -- 
 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.
 

-- 
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] declarative one to many relationship with composite primary key

2010-11-16 Thread Adrien
Hi list,

Sorry if this is trivial, I'm relatively new to sqlalchemy.
I'm trying to set a one to many relationship between class Foo and
class Bar (ie Foo should have a list of Bars). Foo has a composite
primary key.

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


Base = declarative_base()

class Foo(Base):
__tablename__ = foo
one = Column(Integer, primary_key=True)
two = Column(Integer, primary_key=True)

class Bar(Base):
__tablename__ = bar
id = Column(Integer, primary_key=True)
one_id = Column(Integer, nullable=False)
two_id = Column(Integer, nullable=False)

ForeignKeyConstraint([one_id, two_id], [foo.one, foo.two])
foo = relationship(Foo, backref = bars)


metadata = Base.metadata

engine = create_engine('sqlite:///:memory:', echo=True)
metadata.create_all(engine)

from sqlalchemy.orm import sessionmaker

# create a configured Session class
Session = sessionmaker(bind=engine)

# create a Session
session = Session()

foo = Foo()
foo.one = 1
foo.two = 2
session.add(foo)
session.commit()
#

I get the following message:

sqlalchemy.exc.ArgumentError: Could not determine join condition
between parent/child tables on relationship Bar.foo.  Specify a
'primaryjoin' expression.


I tried to change the relationship line to:
foo = relationship(Foo, backref = bars, primaryjoin=and_(one_id ==
Foo.one, two_id==Foo.two ) )

but then I get this message:

sqlalchemy.exc.ArgumentError: Could not determine relationship
direction for primaryjoin condition 'bar.one_id = foo.one AND
bar.two_id = foo.two', on relationship Bar.foo. Ensure that the
referencing Column objects have a ForeignKey present, or are otherwise
part of a ForeignKeyConstraint on their parent Table.

Thank you for your help!

-- 
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.



Re: [sqlalchemy] declarative one to many relationship with composite primary key

2010-11-16 Thread Michael Bayer
ForeignKeyConstraint needs to go into __table_args__ when using declarative.

http://www.sqlalchemy.org/docs/orm/extensions/declarative.html#table-configuration


On Nov 16, 2010, at 6:28 PM, Adrien wrote:

 Hi list,
 
 Sorry if this is trivial, I'm relatively new to sqlalchemy.
 I'm trying to set a one to many relationship between class Foo and
 class Bar (ie Foo should have a list of Bars). Foo has a composite
 primary key.
 
 #
 from sqlalchemy import *
 from sqlalchemy.orm import *
 from sqlalchemy.ext.declarative  import declarative_base
 
 
 Base = declarative_base()
 
 class Foo(Base):
__tablename__ = foo
one = Column(Integer, primary_key=True)
two = Column(Integer, primary_key=True)
 
 class Bar(Base):
__tablename__ = bar
id = Column(Integer, primary_key=True)
one_id = Column(Integer, nullable=False)
two_id = Column(Integer, nullable=False)
 
ForeignKeyConstraint([one_id, two_id], [foo.one, foo.two])
foo = relationship(Foo, backref = bars)
 
 
 metadata = Base.metadata
 
 engine = create_engine('sqlite:///:memory:', echo=True)
 metadata.create_all(engine)
 
 from sqlalchemy.orm import sessionmaker
 
 # create a configured Session class
 Session = sessionmaker(bind=engine)
 
 # create a Session
 session = Session()
 
 foo = Foo()
 foo.one = 1
 foo.two = 2
 session.add(foo)
 session.commit()
 #
 
 I get the following message:
 
 sqlalchemy.exc.ArgumentError: Could not determine join condition
 between parent/child tables on relationship Bar.foo.  Specify a
 'primaryjoin' expression.
 
 
 I tried to change the relationship line to:
 foo = relationship(Foo, backref = bars, primaryjoin=and_(one_id ==
 Foo.one, two_id==Foo.two ) )
 
 but then I get this message:
 
 sqlalchemy.exc.ArgumentError: Could not determine relationship
 direction for primaryjoin condition 'bar.one_id = foo.one AND
 bar.two_id = foo.two', on relationship Bar.foo. Ensure that the
 referencing Column objects have a ForeignKey present, or are otherwise
 part of a ForeignKeyConstraint on their parent Table.
 
 Thank you for your help!
 
 -- 
 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.
 

-- 
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.