简体   繁体   English

Python peewee:如何在连接前选择一列上的不同值?

[英]Python peewee: How to select distinct values on one column before a join?

I try to join a second table (PageLikes) on a first Table (PageVisits) after selecting only distinct values on one column of the first table with the python ORM peewee.在使用 python ORM peewee 在第一个表的一列上仅选择不同的值后,我尝试在第一个表 (PageVisits) 上加入第二个表 (PageLikes)。

In pure SQL I can do this:在纯 SQL 中,我可以这样做:

SELECT DISTINCT(pagevisits.visitor_id), pagelikes.liked_item FROM pagevisits
INNER JOIN pagelikes on pagevisits.visitor_id = pagelikes.user_id

In peewee with python I have tried:在带有python的peewee中,我尝试过:

query = (Page.select(
         fn.Distinct(Pagevisits.visitor_id),
         PageLikes.liked_item)
         .join(PageLIkes)

This gives me an error: distinct() takes 1 positional argument but 2 were given这给了我一个错误: distinct() takes 1 positional argument but 2 were given

The only way I can and have used distinct with peewee is like this:我可以并且已经使用与 peewee 不同的唯一方法是这样的:

query = (Page.select(
         Pagevisits.visitor_id,
         PageLikes.liked_item)
         .distinct()

which does not seem to work for my scenario.这似乎不适用于我的场景。

So how can I select only distinct values in one table based on one column before I join another table with peewee?那么,在使用 peewee 加入另一个表之前,如何根据一列仅选择一个表中的不同值?

I don't believe you should be encountering an error using fn.DISTINCT() in that way.我认为您不应该以这种方式使用fn.DISTINCT()遇到错误。 I'm curious to see the full traceback.我很想看到完整的回溯。 In my testing locally, I have no problems running something like:在我的本地测试中,我运行以下内容没有问题:

query = (PageVisits
         .select(fn.DISTINCT(PageVisits.visitor_id), PageLikes.liked_item)
         .join(PageLikes))

Which produces SQL equivalent to what you're after.它产生的 SQL 相当于你所追求的。 I'm using the latest peewee code btw.顺便说一句,我正在使用最新的 peewee 代码。

As Papooch suggested, calling distinct on the Model seems to work:正如Papooch 所建议的,在 Model 上调用 distinct 似乎有效:

distinct_visitors = (Pagevisits
                            .select(
                                Pagevisits.visitor_id.distinct().alias("visitor")
                            )
                            .where(Pagevisits.page_id == "Some specifc page")
                            .alias('distinct_visitors')
                            )


query = (Pagelikes
         .select(fn.Count(Pagelikes.liked_item),
         )
         .join(distinct_visitors, on=(distinct_visitors.c.visitor = Pagelikes.user_id))
         .group_by(Pagelikes.liked_item)
         )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM