2013-02-15 126 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