2013-02-15 208 views
2

在筆者的模型:'模型' 對象不是可迭代

century = models.ManyToManyField(Century) 

鑑於:

a = get_object_or_404(Author.objects, id=id) 

s = Author.objects.filter(century__in=a).order_by('?')[:3] 

錯誤:

Exception Value: 'Author' object is not iterable

有什麼不對?作者可能屬於兩個世紀,我想從他的世紀/世紀中獲得3位隨機作者。

回答

6
a = get_object_or_404(Author.objects, id=id) 

s = Author.objects.filter(century__in=a.century.all()).order_by('?')[:3] 
3

get_object_or_404()需要類作爲第一個參數。例如

發表評論

a = get_object_or_404(Author, id=id)

更新:

這不是任何地方文檔中提到,但你是正確的。實際上,查看代碼(django/shortcuts/__init__.py)顯示get_object_or_404()get_list_or_404()都可以爲模型,管理器或QuerySet設置其第一個參數。

呵呵。你每天都會學到一些東西!

+1

get_object_or_404確實可以與Author.objects一起使用。 – UnLiMiTeD 2013-02-15 21:51:08

+1

@UnLiMiTeD:趕上!查看更新。 – 2013-02-15 22:07:40