python - 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 个用户的城市?
解决方案
使用注释:
from django.db.models import Count
City.objects.annotate(user_count=Count("user")).filter(user_count__gt=1)
推荐阅读
- python - 发生异常:AttributeError 'Class' 对象没有属性 'Method'
- outlook - Debug Outlook VSTO Plugin from Visual Studio 2017 does not work --> debug not possible removing deployment from Outlook
- java - Java和MySql之间的连接
- excel - 尝试对集合进行排序时类型不匹配
- laravel - Vuejs Laravel Axios 创建请求
- jquery - 添加 data-bv-trigger="null" 使 bootstrapvalidator 只工作一次
- c# - unity 3d ondular 地形生成
- r - R中kmean的创建预测函数
- r - 如何使用自定义函数执行矢量化操作,将结果添加到列表中?
- angular - Angular 6 Http订阅问题:“响应”类型上不存在属性“userInfo”