查询由其他表进一步链接的一元关系

2024-09-24 08:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,我想不出更好的通用标题了。我正在使用金字塔和sqlalchemy构建一个照片投票应用程序。完整的模式和orm在最后,但是最相关的信息是

  1. photo
  2. ^带有photo_iduser_id的{}表,后者标识在照片上投赞成票或反对票的用户。你知道吗
  3. category带有照片类别列表的表
  4. photocategory表链接photocategory

在应用程序的主要照片饲料我想显示以下顺序的照片

  1. 在用户投票的照片之前,用户没有先投票的照片
  2. 在上面的每个组中(未投票,然后投票),按照片的现有投票数降序排序

该应用程序还将有灵活性,显示照片从某些类别只

我现在实施的方式是。。。你知道吗

  • 仅获取所需类别的照片

photos = DBSession.query(Photos).join(photocategory, Photo.id==photocategory.c.photo_id).filter(photocategory.c.category_id==__CATEGORY_ID_HERE__).all()
  • 按票数对photos排序

photos = sorted(photos, key=lambda photo: len(photo.votes), reverse=True)
  • 遍历photos以查看用户是否已经投票,并将照片附加到votedunvoted列表/数组

然而,这是如此低效,因为我必须搜索所有的照片,用户以前投票给每一张照片在photos,所以我想知道什么是正确和有效的方式来做这件事。。。谢谢

模式

  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'),
})

Tags: idtrueschemaormtablecolumninteger投票
1条回答
网友
1楼 · 发布于 2024-09-24 08:35:49

也许使用SQL本身做这件事是个更好的主意。以下是未经测试,可能不会工作,但您可以调整它,以满足您的需要

您可以通过以下方式选择某个类别的照片

cat_photos = session.query(PhotoCategory.photo_id.label('pid')).options(lazyload('*')).filter(PhotoCategory.category_id==SOMEID).subquery()

加入user和photo表以获得用户可以投票的照片列表。假设用户不能对自己的照片进行投票,那么

elig_photos = session.query(User).join(Photos,Photos.user_id!=User.id).options(lazyload('*')).with_entities(Photos.id.label('pid'),User.id.label('uid').subquery()

现在您可以将其加入到投票表和子查询中,以获取用户尚未投票的特定类别的照片

not_voted = session.query(elig_photos).outerjoin(Votes,and_(Votes.photo_id==elig_photos.c.pid,Votes.user_id==elig_photos.c.uid)).join(cat_photos,cat_photos.c.pid==elig_photos.c.pid).with_entities(elig_photos.c.pid.label('photo_id'),Votes.upvote.label('upvote')).options(lazyload('*')).filter(User.id==SOMEUSER).filter(Votes.upvote==None).all()

获取按投票数排序的此类照片。我们将不得不做一个左加入,因为可能有一些照片还没有人投票

sorted_votes = session.query(cat_photos).outerjoin(Votes,cat_photos.c.pid==Votes.photo_id).with_entities(cat_photos.c.pid.label('pid'),func.coalesce(func.sum(Votes.upvote),0).label('sum_votes')).options(lazyload('*')).group_by(cat_photos.pid).order_by(desc('sum_votes')).all()

注意-我为每个查询添加了一个aooptionoptions(lazyload('*')),以使关系延迟加载

现在你有两张单子-

  • sorted_votes按降序列出这类照片 投票顺序(没有人投票的照片0票)
  • not_voted其中列出了未经用户投票的此类照片

请注意,用户上传的此类照片将是第一个列表的一部分

您可以在python中处理这两个列表,首先根据它们在第一个列表中的索引显示not\u voted,然后按原样显示第一个列表的其余部分

not_voted_sorted = sorted(not_voted,key=lambda x:sorted_votes.index(x))
rest_of_the_photos = [y for y in sorted_votes if y not in not_voted]

这将是一个好主意(IMO)如果你只从这些查询得到照片的ID。整个Photo对象列表可以从DB中单独获取,并保存在以Photo\ id为键的字典中。因此,在模板中,如果您知道要显示的照片id,就可以显示整个照片细节。你知道吗

最后一点注意:如果有些东西不起作用,请尝试为您正在尝试的操作编写一个普通的SQL,然后编写与SQLAlchemy等价的语句并打印该语句,以比较手工编写的SQL和SQLAlchemy生成的SQL是否相同

相关问题 更多 >