在Django中从两个具有多对多关系的表中检索数据?

时间:2013-01-14 06:47:07

标签: database django

我想从名为file的表中检索具有用户ID 1的数据。用户和文件表以及多对多的关系。我想显示与该用户相关的文件。

class GalaxyUser(models.Model):
    id = models.IntegerField(primary_key=True)
    create_time = models.DateTimeField(null=True, blank=True)
    update_time = models.DateTimeField(null=True, blank=True)
    email = models.CharField(max_length=765)
    password = models.CharField(max_length=120)
    external = models.IntegerField(null=True, blank=True)
    deleted = models.IntegerField(null=True, blank=True)
    purged = models.IntegerField(null=True, blank=True)
    username = models.CharField(max_length=765, blank=True)
    form_values_id = models.IntegerField(null=True, blank=True)
    disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
    class Meta:
        db_table = u'galaxy_user'

class File(models.Model):
    users = models.ManyToManyField(GalaxyUser)
    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 = models.TextField()
    flag = models.TextField()

如果用户以用户身份登录,我得到user_id,让我们说它是1.现在,我想要检索与用户1相关的文件名。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

您可以使用File.objects.filter(users__id__exact=1)。请参阅here

答案 1 :(得分:1)

File.objects.filter(users=GalaxyUser.objects.get(id=1))

答案 2 :(得分:1)

user = GalaxyUser.objects.get(id=1)
files = user.file_set.all()

详细了解ManyToMany查找here