'QuerySet' object has no attribute 'simplified'

Viewed 44

I am trying to do a fairly simple GET request that leads to a query with DRF:

def get(self, request, character):
    char_entry = Dictionary.objects.filter(Q(simplified=character) | Q(traditional=character))
    serializer = DictionarySerializer(char_entry)
    return Response({"character": serializer.data})

My DictionarySerializer looks like this:

from rest_framework import serializers from .models import Dictionary

class DictionarySerializer(serializers.ModelSerializer):

    class Meta:
        model = Dictionary
        fields = ["id", "simplified", "pinyin_numbers", "pinyin_marks", "translation", "level", "traditional", ]

And my Dictionary model looks like this:

class Dictionary(models.Model):
    traditional = models.CharField(max_length=50)
    simplified = models.CharField(max_length=50)
    pinyin_numbers = models.CharField(max_length=50)
    pinyin_marks = models.CharField(max_length=50)
    translation = models.TextField()
    level = models.IntegerField()

    class Meta:
        db_table = 'dictionary'
        indexes = [
            models.Index(fields=['simplified', ]),
            models.Index(fields=['traditional', ]),
        ]

As far as I can tell, this should serialize all the fields from the Dictionary table, including simplified.

Why can't Django find the attribute? What am I missing?

1 Answers

A QuerySet is a collection of items. It can thus contain zero, one or more items. YOu need to serialize with the many=True parameter:

def get(self, request, character):
    char_entry = Dictionary.objects.filter(
        Q(simplified=character) | Q(traditional=character)
    )
    serializer = DictionarySerializer(char_entry, many=True)
    return Response({'character': serializer.data})

or if we know there is only one item, we should retrieve that single item:

from django.shortcuts import get_object_or_404

def get(self, request, character):
    char_entry = get_object_or_404(
        Dictionary,
        Q(simplified=character) | Q(traditional=character)
    )
    serializer = DictionarySerializer(char_entry, many=True)
    return Response({'character': serializer.data})
Related