2013-02-08 21 views
0

我有兩個模型是這樣的:如何計算在Django中共享文件的用戶數量?

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.txt與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> 

回答

0

也許嘗試呢?

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

由於每個份額對象只對應一個用戶,這給出了Share對象有多少files與主鍵somePk

然後count()只是計數的數量

+0

請參閱我的更新問題。我的查詢是正確的,但我不知道如何以正確的方式在模板中調用它。 – user1881957

相關問題