2012-06-15 120 views
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部分。

什麼是做出這樣的查詢的最佳方式?

回答

2

做一個查詢時,您不需要_set

Image.objects.filter(folders__canaccess__user=current_user) 
+0

我已嘗試沒有_set,但收到錯誤:無法解析關鍵字'canaccess'到字段中。選項是[已聲明模型字段列表] – Drewes

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

而且這似乎解決了這個問題。