Reputation: 2570
I'm learning Django and i got to this error and I couldn't find the solution.
Here are my models
class Retailer(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
website = models.CharField(max_length=255)
def __str__(self):
return str(self.id)
class Product(models.Model):
id = models.AutoField(primary_key=True)
price = models.IntegerField(default=None, null=True)
name = models.CharField(max_length=255)
retailer = models.ForeignKey(Retailer,on_delete=models.CASCADE,related_name='retailer_info')
is_active = models.BooleanField(default=False)
def __str__(self):
return str(self.id)
And here are my serializers
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
class RetailerSerializer(serializers.ModelSerializer):
products = ProductSerializer(many=True, read_only=True)
class Meta:
model = Retailer
fields = ['name', 'website', 'products']
And here's my view
class RetailerList(APIView):
def get(self, request):
retailer = Retailer.objects.all()
serializer = RetailerSerializer(retailer)
return Response(serializer.data)
And here's my url
path('retailer', views.RetailerList.as_view()),
But when I submit a get request on 127.0.0.1:8000/retailer i get this error:
AttributeError at /product Got AttributeError when attempting to get a value for field
name
on serializerRetailerSerializer
. The serializer field might be named incorrectly and not match any attribute or key on theQuerySet
instance. Original exception text was: 'QuerySet' object has no attribute 'name'. What's the problem?
Upvotes: 1
Views: 1779
Reputation: 476997
You should add many=True
in the RetailerSerializer
, since you are not serializing a single element, but a list of elements. Furthermore you should for example return this as aJsonResponse
:
from django.http import JsonResponse
class RetailerList(APIView):
def get(self, request):
retailer = Retailer.objects.all()
serializer = RetailerSerializer(retailer, many=True)
return JsonResponse({'data': serializer.data})
Upvotes: 2