1

使用这样的模型:

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)

FieldError当 Django 查找该canaccess_set部分时,我得到一个。

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

4

2 回答 2

2

_set进行查找时不需要:

Image.objects.filter(folders__canaccess__user=current_user)
于 2012-06-15T12:54:16.550 回答
0

好的,在这里找到的信息:

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

表明模型的加载顺序可能会产生这种 og 错误,所以我从这个顺序更改了 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()

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

于 2012-06-16T19:35:15.973 回答