Django中的一对多查询

时间:2019-03-14 20:02:03

标签: python django django-queryset

这是我的城市对象:

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

1 个答案:

答案 0 :(得分:2)

使用注释:

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