gpt4 book ai didi

mysql - 如何将此 MySQL 查询转换为 Django 查询?

转载 作者:行者123 更新时间:2023-11-29 13:58:34 28 4
gpt4 key购买 nike

我有一个这样的查询:

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]

模型.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()

我怎样才能做到这一点?谢谢

最佳答案

尝试这样的事情:

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

关于mysql - 如何将此 MySQL 查询转换为 Django 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15432049/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com