简体   繁体   中英

Django Queryset: Only return entries where a specific field appears greater than N times

Let's say I have a model with a user foreignkey and a charfield.

How can I filter a queryset so that only users with > 3 entries are returned in one line?

So something like this (which obviously does not exist yet):

Post.objects.filter(user__appears__gte=2)

EDIT: updated answer after understanding question

Not the best solution but you can loop for each user in the User object and then check the number of counts it appears in the Post object, if greater than 2 return those Post objects.

all_posts = Post.objects.none()
all_users = User.objects.all()

for user in all_users:
    user_posts = Post.objects.filter(user=user)
    if user_posts.count() > 2:
        all_posts = all_posts | user_posts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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