0

This is my City object:

class City(Base):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    latitude = models.FloatField()
    longitude = models.FloatField()

And this is my user:

class User(AbstractBaseUser, PermissionsMixin, Base):
    username = models.CharField(db_index=True, null=False, unique=True, max_length=255)
    mobile = models.CharField(db_index=True, max_length=100, null=True, unique=True)
    city = models.ForeignKey(City, on_delete=models.CASCADE, null=True)

How do I query cities which have more than 1 user?

1 Answer 1

2

Use annotations:

from django.db.models import Count
City.objects.annotate(user_count=Count("user")).filter(user_count__gt=1)
Sign up to request clarification or add additional context in comments.

5 Comments

Does this return the count of cities with more than one user?
No, it returns the cities, not the count.
This gives me a syntax error, is this complete code?
Sorry, missed a close parenthesis, try it now.
Yup works now, I'm using it as city_count = City.objects.annotate(user_count=Count("user").filter(user_count__gt=1).count()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.