0

I need to return random data from models in json format but when I try random.choice I got the error 'Joke' object is not iterable .

views.py

def random_page(request):
   random_joke = random.choice(Joke.objects.all())

   jokes_list = serializers.serialize('json', random_joke)
   return HttpResponse(jokes_list, content_type="text/json-comment-filtered")

models.py

from django.db import models

class Joke(models.Model):
    joke = models.TextField(max_length=1000)
    author = models.CharField(max_length=100, null=True)

    def __str__(self):
        return str(self.joke)

1 Answer 1

1

Acutally the issue is serializers.serialize expects an iterable i.e object that can be iterated. You are passing single object which is not iterable. So better to add the object in iterable like list

jokes_list = serializers.serialize('json', [random_joke])
Sign up to request clarification or add additional context in comments.

1 Comment

Np. Title should be like serializing random object of queryset.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.