Hi all, I want to know if I am using SQLAlchemy in a correct and proper way for Many to One Relations between objects and database tables. I have created a test case for Cars and Brands. Each car can have a name and one Brand. I wonder if I use the setter in the Car Class correctly and if the assignement in the car mapper is correct also. Just to be clear, it is working, but I want to know if I use everything correctly here.
Many thanks for your comments Frank CODE: #!/usr/bin/python # coding: utf-8 from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey from sqlalchemy.orm import mapper, sessionmaker, relation, backref engine = create_engine('sqlite:///:memory:', echo=True) class Car(object): def __init__(self, name): self.name = name self.brand = None self.brand_id = None def setBrand(self, brand): self.brand_id = brand.id self.brand = brand class Brand(object): def __init__(self, name): self.name = name metadata = MetaData() brands = Table('brands', metadata ,Column('id', Integer, primary_key=True) ,Column('name', String(10), nullable=False)) cars = Table('cars', metadata ,Column('id', Integer, primary_key=True) ,Column('name', String(10), nullable=False) ,Column('brand_id', Integer, ForeignKey('brands.id'))) metadata.create_all(engine) mapper(Car, cars, properties={'brand': relation(Brand)}) mapper(Brand, brands) Session = sessionmaker(bind=engine, autoflush=True) ps = Session() porsche = Brand('Porsche') bmw = Brand('BMW') audi = Brand('Audi') # some Audis a4 = Car('A4 quattro') a4.setBrand(audi) a6 = Car('A6') a6.setBrand(audi) # a BMW i326 = Car('i326') i326.setBrand(bmw) ps.add(a4) ps.add(a6) ps.add(i326) res = ps.query(Car) for a_car in res: print a_car.brand.name -- Frank Broniewski Metrico s.àr.l. ( http://www.metrico.lu ) 36, rue des Romains L-5433 Niederdonven Luxembourg Fon: +352 26 74 94 28 Fax: +352 26 74 94 99 --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---