Denzel
Denzel

Reputation: 449

How to return all data in database as Json?

How to return all data in database as Json? Models.py:

class Hero(models.Model):
    Hero_id = models.IntegerField(auto_created=True, primary_key=True, serialize=False, verbose_name='Hero_id')
    race = models.CharField(max_length=50, blank=True)
    age = models.IntegerField(blank=True)
    class_= models.CharField(max_length=50, blank=True)

Views.py:

class HeroSerializer(serializers.ModelSerializer):
    class Meta:
        model = Hero
        fields = ['Hero_id', 'race', 'age', 'class_']
        extra_kwargs = {
                'race': {
                    'required': False,
                    'allow_null':True
                 },
                'age': {
                    'required': False,
                    'allow_null':True
                 },
                'class_': {
                    'required': False,
                    'allow_null':True
                 }
            }
def HHH():
    h=Hero.objects.all()
    serializer= HeroSerializer(h)
    return JsonResponse(serializer.data)

But it returns me an error: Got AttributeError when attempting to get a value for field Hero_id on serializer HeroSerializer. The serializer field might be named incorrectly and not match any attribute or key on the str instance. Original exception text was: 'str' object has no attribute 'Hero_id'. Any ideas?

Upvotes: 0

Views: 96

Answers (1)

funnydman
funnydman

Reputation: 11366

Because you're serializing a bunch of instances you need to pass many=True to the serializer:

def HHH():
    h=Hero.objects.all()
    serializer= HeroSerializer(h, many=True)
    return JsonResponse(serializer.data, safe=False)

Take a look at the examples provided by the documentation. Also, field name class_ is not valid at least in Django 2.x and you'll get the error:

ERRORS:
core.Hero.class_: (fields.E001) Field names must not end with an underscore.

To render into the template (assumed it's configured properly) you could use render function, e.g.

views.py

from django.shortcuts import render

def HHH():
    heros = Hero.objects.all()
    serializer = HeroSerializer(heros, many=True)
    return render(request, 'index.html', {'heros': serializer.data})

index.html

{% for hero in heros %}
    <p>{{ hero.age }}</p>
{% endfor %}

Upvotes: 1

Related Questions