user1881957
user1881957

Reputation: 3388

How to know the owner who shared this file in this context in Django?

I have a table like this:

+----+----------+----------+----------------+----------------------------------+
| id | users_id | files_id | shared_user_id | shared_date                      |
+----+----------+----------+----------------+----------------------------------+
|  3 |        1 |        1 |              2 | 2013-01-31 14:27:06.523908+00:00 |
|  2 |        1 |        1 |              2 | 2013-01-31 14:25:37.760192+00:00 |
|  4 |        1 |        3 |              2 | 2013-01-31 14:46:01.089560+00:00 |
|  5 |        1 |        1 |              3 | 2013-01-31 14:50:54.917337+00:00 |

Now I want to know the owner of each files who shared the file. For file 1, users_id is 1. I want to get the name of users_id 1 from the default Django auth_user table. I want to get the usernames for each file. How can I do that?

#models.py
from django.db import models
from django.contrib.auth.models import User

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()

class Host(models.Model):
    name = models.TextField()
    full_path = models.TextField()

Upvotes: 0

Views: 25

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

As I've said to you before, your model structure is a bit odd - in particular, Share.shared_user should be a ForeignKey, not an IntegerField. In this case, you could help things by making users a ManyToManyField from File to User, using Share as the through table:

class File(models.Model):
    users = models.ManyToManyField(User, through='Share')

Now given a File instance you can simply do:

my_file.users.count()

Upvotes: 1

Related Questions