DISTINCT关键字在Django中的MYSQL后端?

时间:2021-09-04 14:26:21

I hae a MYSQL query like this:

我有这样的MYSQL查询:

shared_file = File.objects.filter(id__in= Share.objects.filter(user_id = log_id).values_list('file', flat=True)).annotate(count=Count('share__shared_user_id')).distinct()

I am trying to get all the file information along with the number of people the file is shared. I want shared_user_id from Share model to be DISTINCT. My two models File and Share are:

我试图获取所有文件信息以及文件共享的人数。我希望Share模型的shared_user_id为DISTINCT。我的两个模型文件和共享是:

class File(models.Model):
    user = models.ForeignKey(User)
    file_name = models.CharField(max_length=100)
    type = models.CharField(max_length=10)              #File extension
    source = models.CharField(max_length=100)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    size = models.CharField(max_length=50)              #Stored in humansize
    flag = models.CharField(max_length=1)               #Flag to show deleted files
    flag_overview = models.CharField(max_length=1)      #Flag to remove file from 

class Share(models.Model):
    user = models.ForeignKey(User)
    file = models.ForeignKey(File)
    shared_user_id = models.IntegerField()
    shared_date = models.DateTimeField()

How can I achieve this? Thanks

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

1 个解决方案

#1


0  

try

shared_file = File.objects.filter(id__in =
                                  Share.objects.filter(user_id = log_id)
                                               .values_list('file', flat=True))
                          .annotate(count=Count('share__shared_user_id',
                                                distinct=True))

#1


0  

try

shared_file = File.objects.filter(id__in =
                                  Share.objects.filter(user_id = log_id)
                                               .values_list('file', flat=True))
                          .annotate(count=Count('share__shared_user_id',
                                                distinct=True))