I have my two class in two separate files, customer and address. Address is going to be used in other places for instance vendors have addresses. The customer class needs to reference the address class in three ways. A customer has a default ship to address (one to one) a default bill to address (one to one) and his a list of multiple addresses that can be selected if the defaults aren’t needed.
The customer class in the ar.py file and the address class is in the global.py file.
The one to ones just work but the one to many list I can’t figure out how to make it work with the classes in two different files. With out circular issues.
Thanks for any insights you can provide …
globals.py
from erp.model import DeclarativeBase, metadata, DBSession
class Address(DeclarativeBase):
__tablename__ = 'addresses'
address_id = Column(Integer,primary_key=True)
name = Column(Unicode(100))
address_one = Column(Unicode(100))
address_two = Column(Unicode(100))
address_three = Column(Unicode(100))
city = Column(Unicode(100))
state = Column(Unicode(100))
zip_code = Column(Unicode(100))
phone = Column(Unicode(100))
fax = Column(Unicode(100))
contact = Column(Unicode(100))
ar.py ...
from erp.model.globals import Address
class Customer(DeclarativeBase):
__tablename__ = 'customers'
customer_id = Column(Integer, primary_key=True)
customer_name = Column(Unicode(100))
discount = Column(Float)
#bill_to_id = Column(Integer, ForeignKey('addresses.address_id'))
#bill_to = relation(Address,primaryjoin=bill_to_id==Address.address_id,uselist=False)
ship_to_id = Column(Integer, ForeignKey('addresses.address_id'))
ship_to = relation(Address,primaryjoin=ship_to_id==Address.address_id,uselist=False)
locations = relation(Address,backref="customer",primaryjoin='customers.customer_id'=='addresses.customer_id')
I can make this work just fine if i have everything in one file however this over complicates the project layout with having a bunch of stuff in one file or worse duplication the same kind of layout of class address in the ar file and also in the vendor file.
Again thanks for your help!
Paul
You can create models using strings instead of instances. For example
SQLAlchemy will handle turning these into objects.
A one to many is typically handled via a fkey on addresses pointing back to the customers. However this won’t work well if you are using the addresses for multiple purposes. If you want all of the addresses in your database to be stored in a single table, then I’d suggest adding link tables between each table and addresses. For example customer_addresses would have fkeys to addresses and customers. The other option is to make a separate table for customer_addresses vs vendor_addresses. If you’d like to do this the best way would be to create an
AddressMixinwhich you could apply to different objects: