gioi
gioi

Reputation: 1483

Peewee ORM - annotate count on many-to-many relation even if count is 0

Let's try to explain my problem using users and tweets.

These are my models (from Peewee docs):

class User(BaseModel):
    username = CharField()

class Tweet(BaseModel):
    user = ForeignKeyField(User, related_name='tweets')
    message = TextField()

and this is my query:

User.select().annotate(Tweet).order_by(fn.Count(Tweet.id).desc())

I have some users that haven't already tweeted, but I'd like anyway to get them with my query. Unfortunately, this query doesn't work for users without tweets.

How can I solve this problem?

Upvotes: 2

Views: 1256

Answers (1)

gioi
gioi

Reputation: 1483

Ok, I solved.

If you have my problem, simply use OUTER JOIN.

Here is my new query:

User.select(User, fn.Count(Tweet.id).alias('count')) \
    .join(Tweet, JOIN_LEFT_OUTER).group_by(User)

Upvotes: 3

Related Questions