Adam
Adam

Reputation: 3128

'Model' object is not iterable

In author model:

century = models.ManyToManyField(Century)

In view:

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

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

Error:

Exception Value: 'Author' object is not iterable

What's wrong? The author may belong to two centuries and I want to get 3 random authors from his century/centuries.

Upvotes: 2

Views: 5194

Answers (2)

Peter Rowell
Peter Rowell

Reputation: 17713

get_object_or_404() takes a class as the first arg. e.g.

a = get_object_or_404(Author, id=id)

Update for comment:

It's not mentioned anywhere in the docs, but you are correct. In fact, looking at the code (django/shortcuts/__init__.py) shows that that get_object_or_404() and get_list_or_404() can both take a Model, a Manager, or a QuerySet for their first arg.

Huh. You learn something every day!

Upvotes: 3

UnLiMiTeD
UnLiMiTeD

Reputation: 1040

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

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

Upvotes: 6

Related Questions