Python 在Django中注释多对多关系
我有两个模型用户和视频数据。这两个模型包含每个用户的详细信息以及该用户观看的视频。我使用多对多关系。现在我想按用户数量筛选前10名观看的视频Python 在Django中注释多对多关系,python,django,django-models,Python,Django,Django Models,我有两个模型用户和视频数据。这两个模型包含每个用户的详细信息以及该用户观看的视频。我使用多对多关系。现在我想按用户数量筛选前10名观看的视频 class User(models.Model): user_id = models.CharField(max_length=40,unique=True) user_name = models.CharField(max_length=40) user_email = models.EmailField() user_c
class User(models.Model):
user_id = models.CharField(max_length=40,unique=True)
user_name = models.CharField(max_length=40)
user_email = models.EmailField()
user_city = models.CharField(max_length=40)
videos_watched = models.ManyToManyField('VideoData', through='WatchedVideo')
class Meta:
ordering = ['user_id']
verbose_name = 'User MetaData'
verbose_name_plural = 'Users MetaData'
def __unicode__(self):
return self.user_id
class VideoData(models.Model):
video_id = models.CharField(max_length=40,unique=True)
video_name = models.CharField(max_length=40)
class Meta:
verbose_name = 'User_Video MetaData'
verbose_name_plural = 'Users_Video MetaData'
def __unicode__(self):
return self.video_name
class WatchedVideo(models.Model):
user = models.ForeignKey(User, to_field = 'user_id')
videoData = models.ForeignKey(VideoData, to_field = 'video_id')
time = models.PositiveIntegerField(null = True)
如何为前10名视频和观看这些视频的用户数添加注释???使用django ORM的计数功能:
VideoData.objects.annotate(
watches_count=models.Count('user_set')
).order_by('-watches_count')[:10]
使用django ORM中的计数函数:
VideoData.objects.annotate(
watches_count=models.Count('user_set')
).order_by('-watches_count')[:10]
WatchedVideo
中的时间是多少?是用户观看视频的次数吗?@cezar no time Is watched time,即观看视频的时间。请注意编码惯例:最好将WatchedVideo
中的videoData
重命名为video\u data
,以符合其余内容。@cezar.我将如何根据这些数据筛选前10个城市用户数量…我使用了“user.objects.annotate(city\u count=models.count('user\u city'))。order\u by('-city\u count'))[:10]”。。。。。。。。。。。。但我总是得到city_count=1..你确定数据库中有多个用户的城市吗?在观看的视频中时间是多少?是用户观看视频的次数吗?@cezar no time Is watched time,即观看视频的时间。请注意编码惯例:最好将WatchedVideo
中的videoData
重命名为video\u data
,以符合其余内容。@cezar.我将如何根据这些数据筛选前10个城市用户数量…我使用了“user.objects.annotate(city\u count=models.count('user\u city'))。order\u by('-city\u count'))[:10]”。。。。。。。。。。。。但我总是得到city_count=1.你确定数据库中有多个用户的城市吗?伙计,你真是个天才!只是一个补充信息:OP应该将此查询集分配给一个变量,比如说videos
,然后调用像这样观看视频的次数:videos[0]。观看排名第一的视频。你可以这样做:User.objects.annotate(city\u count=models.count('User\u city')。order\u by('-city\u count'))[:10]@尤金·索尔达托夫总是不工作,我要去城里了,伙计,你真是个天才!只是一个补充信息:OP应该将此查询集分配给一个变量,比如说videos
,然后调用像这样观看视频的次数:videos[0]。观看排名第一的视频。你可以这样做:User.objects.annotate(city\u count=models.count('User\u city')。order\u by('-city\u count'))[:10]@EugeneSoldatov不经常工作我得到了城市计数=1