如何将这个MySQL查询转换为Django查询?

时间:2013-03-15 12:06:47

标签: mysql django django-queryset

我有这样的查询:

select files_id, count(DISTINCT shared_user_id) FROM fileupload_share GROUP BY files_id;

我想在Django查询中转换。试过这样:

count = Share.objects.filter(users_id=request.user.id).values_list('shared_user_id').distinct().count()

但不按要求输出给我一组。我希望输出在像

这样的列表中返回
count = [1, 2, 3, 1]

models.py:

class Share(models.Model):
    users = models.ForeignKey(User)
    files = models.ForeignKey(File)
    shared_user_id = models.IntegerField()
    shared_date = models.TextField()

class File(models.Model):
    users = models.ForeignKey(User)
    file_name = models.CharField(max_length=100)
    type = models.CharField(max_length=10)
    source = models.CharField(max_length=100)
    start_date = models.TextField()
    time_overview = models.CharField(max_length=55)
    end_date = models.TextField()
    duration = models.TextField()
    size_overview = models.IntegerField()
    size = models.TextField()
    flag = models.TextField()
    flag_r = models.TextField()

我该怎么做?感谢

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

files = File.objects.filter(users_id=request.user.id).annotate(count=Count('share__shared_user_id')

然后你应该

for f in files:
    print f.file_name, f.count