對不起,我想不出一個更好的通用標題。我正在使用金字塔和sqlalchemy構建一個照片投票應用程序。完整的模式和ORM是在最後,但最相關的信息是查詢其他表進一步鏈接的一對多關係
photo
表vote
表photo_id
和user_id
,後者標識或者誰投贊成票上下照片中的用戶。category
表照片分類列表photocategory
臺聯photo
和category
表
在應用程序的主照片供稿我想顯示的照片按以下順序
- 用戶未投票的照片,他/她已投票
- 以上各組內(未投票和ñ投票),排序下降的照片
該應用程序的現有投票數的順序也將可以靈活地顯示某些品類只有
我現在實現的方式是照片...
- 只獲得了照片所需的類別
即
photos = DBSession.query(Photos).join(photocategory, Photo.id==photocategory.c.photo_id).filter(photocategory.c.category_id==__CATEGORY_ID_HERE__).all()
- 通過投票
即
photos = sorted(photos, key=lambda photo: len(photo.votes), reverse=True)
- 通過
photos
迭代次數排序photos
來查看用戶是否已經投票,和照片添加到任何一個voted
或unvoted
list/array
但是,這是如此低效,因爲我必須搜索用戶以前投過的所有照片,因爲我在photos
的每張照片中都有投票,所以我想知道什麼是正確和有效的方法來做到這一點......謝謝
SCHEMA
photo_table = schema.Table('photo', metadata,
schema.Column('id', types.Integer,
schema.Sequence('photo_seq_id'), primary_key=True),
schema.Column('caption', types.UnicodeText(), nullable=True),
schema.Column('timestamp', types.TIMESTAMP(), default=datetime.now()),
schema.Column('last_updated', types.TIMESTAMP(), default=datetime.now(),),
schema.Column('spam', types.Boolean, default=0),
schema.Column('trash', types.Boolean, default=0),
schema.Column('image_path', types.Unicode(255), nullable=False),
schema.Column('user_id', types.Integer, schema.ForeignKey('user.id', ondelete='CASCADE')),
mysql_engine='InnoDB'
)
category_table = schema.Table('category', metadata,
schema.Column('id', types.Integer,
schema.Sequence('category_seq_id'), primary_key=True),
schema.Column('name', types.Unicode(255), nullable=False, unique=True),
mysql_engine='InnoDB'
)
photocategory_table = schema.Table('photocategory', metadata,
schema.Column('photo_id', types.Integer, schema.ForeignKey('photo.id', ondelete='CASCADE'), primary_key=True),
schema.Column('category_id', types.Integer, schema.ForeignKey('category.id', ondelete='CASCADE'), primary_key=True),
mysql_engine='InnoDB'
)
vote_table = schema.Table('vote', metadata,
schema.Column('id', types.Integer,
schema.Sequence('vote_seq_id'), primary_key=True),
schema.Column('timestamp', types.TIMESTAMP(), default=datetime.now()),
schema.Column('upvote', types.Boolean, nullable=False),
schema.Column('photo_id', types.Integer, schema.ForeignKey('photo.id', ondelete='CASCADE')),
schema.Column('user_id', types.Integer, schema.ForeignKey('user.id', ondelete='CASCADE')),
mysql_engine='InnoDB'
)
ORM映射
orm.mapper(Photo, photo_table, properties={
'votes': orm.relation(Vote, backref='photo', lazy='dynamic'),
'categories': orm.relation(Category, secondary=photocategory_table, backref='photos'),
})
orm.mapper(User, user_table, properties={
'photos': orm.relation(Photo, backref='owner'),
'votes': orm.relation(Vote, backref='voter', lazy='dynamic'),
})