这是我的城市对象:
class City(Base):
country = models.ForeignKey(Country, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
latitude = models.FloatField()
longitude = models.FloatField()
这是我的用户:
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)
如何查询用户超过1个的城市?
答案 0 :(得分:2)
使用注释:
from django.db.models import Count
City.objects.annotate(user_count=Count("user")).filter(user_count__gt=1)