本文介绍了在Django中注释多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型User和VideoData。这两个模型包含每个用户的详细信息以及该用户观看的视频。我使用了多对多关系。现在,我想按用户数量过滤观看次数最多的10个视频。
I have two models User and VideoData. These two models contain the details of each user and watched videos by that user. I used many-to-many relation. Now I want to filter top 10 videos watch by number of users.
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个视频以及观看这些视频的用户数量?
How can i annotate for top 10 videos and number of users watched those videos??
推荐答案
使用Django ORM中的Count函数:
Use Count function from django ORM:
VideoData.objects.annotate(
watches_count=models.Count('user_set')
).order_by('-watches_count')[:10]
这篇关于在Django中注释多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!