0

我有一张这样的桌子:

+----+----------+----------+----------------+----------------------------------+
| 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 |

现在我想知道共享文件的每个文件的所有者。对于文件 1,users_id 为 1。我想从默认的 Django auth_user 表中获取 users_id 1 的名称。我想获取每个文件的用户名。我怎样才能做到这一点?

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

1 回答 1

1

正如我之前对你说过的,你的模型结构有点奇怪——特别是Share.shared_user应该是 ForeignKey,而不是 IntegerField。在这种情况下,您可以通过将usersManyToManyField from Fileto用作表格User来帮助解决问题:Sharethrough

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

现在给定一个File实例,您可以简单地执行以下操作:

my_file.users.count()
于 2013-01-31T10:36:24.643 回答