0

我有两个这样的模型:

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()
    end_date = models.TextField()
    duration = models.TextField()
    size_overview = models.IntegerField()
    size = models.TextField()
    flag = models.TextField()
    #delete_date = models.CharField(max_length=100, null=True, blank=True)

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

我想计算共享文件的人。例如,如果文件 ok.t​​xt 与 2 人共享,我想显示 file_information 并显示 shared_with coloumn 2 的值。我这样做:

    file_s = Share.objects.filter(users_id=log_id)
 shared_with = Share.objects.filter(files_id__in = file_s).values_list('shared_user_id', flat=True).distinct().count() 

但它为每个文件显示相同的 shared_with 编号。我究竟做错了什么?

编辑:实际上我的查询是正确的,但我不知道如何在模板中调用它:

#views.py
def shared_by_me(request):
    try: 
        log_id = request.user.id
        username = request.user.username

        #Shared by me file information
        file_s = Share.objects.filter(users_id=log_id)

        b = [i.files_id for i in file_s]
        c = map(str, b)
        c = ''.join(c)
        shared_with = Share.objects.filter(files_id__in = file_s).values_list('shared_user_id', flat=True).distinct().count() 
        shared_file = File.objects.filter(id__in= Share.objects.filter(users_id = log_id).values_list('files', flat=True))
        #shared_username = User.objects.filter(id__in= Share.objects.filter(users_id = log_id).values_list('shared_user_id', flat=True))
        shared_username = Share.objects.filter(shared_user_id=log_id)
        #shared_file = File.objects.filter(id__in = c, users__id = log_id)
        return render_to_response('shared_by_me.html', {'shared_by_me':shared_file, 'shared_with':shared_with, 'username':username, 'shared_username':shared_username}, context_instance=RequestContext(request))
    except ValueError:
        return render_to_response('shared_by_me.html', {'username':username}, context_instance=RequestContext(request))

#template:
    {% for choice in shared_by_me %}
            <tr class="oddclass">
              <td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" onchange="checkChecked()"/></td>
              <td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>
              <td>{{ choice.type }}</td>
              <td>{{ choice.size }}</td>
              <td>{{ choice.end_date }}</td>
              <td><a href="#" onclick="share()">{{ shared_with }}</a></td>
              {% endfor %}

            </tr>
4

1 回答 1

0

也许试试这个?

file_s = Share.objects.filter(files__pk = somePk).count()

由于每个共享对象只对应一个用户,这给出了有多少Share对象具有files主键somePk

然后count()只计算数字

于 2013-02-08T04:36:38.833 回答