首页 > 解决方案 > Django中的一对多查询

问题描述

这是我的城市对象:

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 个用户的城市?

标签: pythondjangodjango-queryset

解决方案


使用注释:

from django.db.models import Count
City.objects.annotate(user_count=Count("user")).filter(user_count__gt=1)

推荐阅读