Simon,
On 25/01/2010 15:18, King Simon-NFHD78 wrote:
...
I hope that helps,
Yes, that did help a lot.
This is my custom property class.
class TranslationProperty(object):
"""Returns a query enabled property
"""
def __init__(self, tTable=None, fCol=None, cLang=None, dLang=None):
self.tTable = tTable
self.fCol = fCol
self.cLang = cLang
self.dLang = dLang
def __get__(self, obj, objtype):
# get the class containing the translations
tTable = globals()[self.tTable]
# get the column containing the translation code, e.g. "EN_en"
fCrit = getattr(tTable, self.fCol)
try:
return
sao.object_session(obj).query(tTable).with_parent(obj).filter(fCrit==self.cLang).one()
except sao.exc.NoResultFound:
try:
return
sao.object_session(obj).query(tTable).with_parent(obj).filter(fCrit==self.dLang).one()
except sao.exc.NoResultFound:
return 'no translation found'
Then this is my country table with columns which don't need translation:
class Country_B(Base):
__table__ = sa.Table(u'countries_b', metadata,
sa.Column(u'id', sa.Integer(), sa.Sequence('countries_b_id'),
primary_key=True, nullable=False),
sa.Column(u'iso2', sa.String(length=2, convert_unicode=False)),
sa.Column(u'iso3', sa.String(length=3, convert_unicode=False)),
...
)
country_t = sao.relation('Country_T', backref='country_b')
country = TranslationProperty('Country_T', 'lang_code5',
getCurrentUserLang, getDefaultUserLang)
The table with translation columns:
class Country_T(Base):
__table__ = sa.Table(u'countries_t', metadata,
sa.Column(u'id', sa.Integer(), sa.Sequence('countries_t_id'),
primary_key=True, nullable=False),
sa.Column(u'lang_code5', sa.String(length=5,
convert_unicode=False), sa.ForeignKey(u'languages.code5')),
sa.Column(u'name', sa.String(length=50, convert_unicode=False)),
....
sa.Column(u'countries_b_id', sa.Integer(),
sa.ForeignKey(u'countries_b.id')),
)
Then using it like this:
db.setCurrentUserLang('FR_fr')
ct = session.query(db.Country_B)
for x in ct:
print x
print x.country
print x.country.name
db.setCurrentUserLang('DE_de')
for x in ct:
print x
print x.country
print x.country.name
Resulting in this:
Country_B(id=2, iso2=u'FR', iso3=u'FRA')
Country_T(countries_b_id=2, id=3, lang_code5=u'EN_en', name=u'France')
France
Country_B(id=2, iso2=u'FR', iso3=u'FRA')
Country_T(countries_b_id=2, id=4, lang_code5=u'DE_de', name=u'Frankreich')
Frankreich
The test db does not contain an "FR_fr" translation, and the default
language is set to "EN_en".
Now I just need to clean up the code, document it a bit and add better
error handling.
Simon and Michael, thanks again for helping me with all this.
Hope above might be useful for others.
Werner
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.