开发者

SQLAlchemy: relation in mappers compile result of function rather than calling the function when the relation is queried

开发者 https://www.devze.com 2022-12-09 13:02 出处:网络
I have a number of mappers that look like this: mapper(Photo,photo_table, properties = { \"locale\": relation(PhotoContent, uselist=False, primaryjoin=and_(photo_content_table.c.photoId == photo_tabl

I have a number of mappers that look like this:

mapper(Photo,photo_table, properties = { "locale": relation(PhotoContent, uselist=False, primaryjoin=and_(photo_content_table.c.photoId == photo_table.c.id, photo_content_table.c.locale == get_lang()), foreign_keys=[photo_content_table.c.photoId, photo_content_table.c.locale])

I have deployed in Pylons, the so the get_lang() function should return either "en" or "es" based on the current session.

from pylons.i18n import get_lang

The problem is that SA compiles开发者_开发技巧 that "locale" relation with the result returned by get_lang() at compile time. So if I do something like this:

meta.Session.query(Photo).options(eagerload('locale')).get(id)

The relation does not call get_lang(). It just uses whatever the value of get_lang() was at compile time.

Anyone have any ideas how to implement SQLAlchemy eagerloaders that are dynamic? This would be a lifesaver for me!


The relation statements gets executed when the class is loaded, which means every function call gets evaluated.

Try passing the function instead:

and_(photo_content_table.c.photoId == photo_table.c.id, photo_content_table.c.locale == get_lang)

Note the missing parenthesis. It now should get evaluated whenever the relation gets queried.

0

精彩评论

暂无评论...
验证码 换一张
取 消