Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

One table for multiple images associated with one object/model #17

Open
mattupstate opened this issue Jan 21, 2014 · 2 comments
Open

One table for multiple images associated with one object/model #17

mattupstate opened this issue Jan 21, 2014 · 2 comments

Comments

@mattupstate
Copy link

Is it possible to use one table for all the images associated with one object/model? It appears that two tables are required as illustrated by the UserPicture and UserFrontCover relationships in the sqlalchemy_imageattach.entity module documentation.

I'd much prefer something like:

class User(Base):
    avatar_image = image_attachment('UserImage')
    background_image = image_attachment('UserImage')

Given the above model, SQLAlchemy can't determine the join condition. When I've come across this before, I generally have the foreign key on the "parent", in this case the User model and looks like this:

class User(Base):
    avatar_image_id = Column(Integer, ForeignKey('user_images.id'))
    avatar_image = relationship('UserImage', foreign_keys=avatar_image_id)
    background_image_id = Column(Integer, ForeignKey('user_images.id'))
    background_image = relationship('UserImage', foreign_keys=background_image_id)

Is there a reason you chose to store the foreign key on the Image model? Is there a way of getting around requiring two tables? Or am I just missing some configuration option to avoid using two tables?

@mattupstate
Copy link
Author

Actually, I just realized I can probably do this:

class UserImage(Image, Base):
    __tablename__ = 'user_images'

class User(Base):
    avatar_image_id = db.Column(db.Integer, db.ForeignKey('user_images.id'))
    avatar_image = image_attachment('UserImage', 
        foreign_keys=avatar_image_id, single_parent=True)
    background_image_id = db.Column(db.Integer, db.ForeignKey('user_images.id'))
    background_image = image_attachment('UserImage', 
        foreign_keys=background_image_id, single_parent=True)

@dahlia
Copy link
Owner

dahlia commented Jan 22, 2014

You can put any arbitrary columns to UserImage class e.g. type, and union two types of images (avatar_image and background_image) into one table and distinguish two by filtering type column.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants