嵌套的外键查询

时间:2012-06-15 12:32:03

标签: django foreign-keys nested

使用这样的模型:

class Folder(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField()

class CanAccess(models.Model):
    folder = models.ForeignKey(Folder)
    user = models.ForeignKey(User)

class Image(models.Model):
    folders = models.ManyToManyField('Folder')
    title = models.CharField()

我需要找到用户可以访问的所有图像。

我试过这个,但它不起作用:

images=Image.objects.filter(folders__canaccess_set__user=current_user)

当Django查找FieldError部分时,我得到canaccess_set

什么是进行此类查询的最佳方式?

2 个答案:

答案 0 :(得分:2)

进行查找时不需要_set

Image.objects.filter(folders__canaccess__user=current_user)

答案 1 :(得分:0)

好的,这里的信息是:

http://bitkickers.blogspot.dk/2010/04/django-manytomany-error-cannot-resolve.html

表示模型的加载顺序可能会产生这种类型的错误,所以我从这个顺序更改了models.py文件:

class Image(models.Model):
    folders = models.ManyToManyField('Folder')
    title = models.CharField()

class Folder(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField()

class CanAccess(models.Model):
    folder = models.ForeignKey(Folder)
    user = models.ForeignKey(User)

这个顺序:

class CanAccess(models.Model):
    folder = models.ForeignKey("Folder")
    user = models.ForeignKey(User)

class Image(models.Model):
    folders = models.ManyToManyField('Folder')
    title = models.CharField()

class Folder(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField()

这实际上似乎解决了这个问题。