Reputation: 788
I have imported the Django model Product
into the DRF model serializer class, but I get the error Class ProductSerializer missing "Meta.model" attribute
. What surprises me is that the model is set on the Meta
class. What I'm I doing wrong?
AssertionError at /api/products/
Class ProductSerializer missing "Meta.model" attribute
Request Method: GET
Request URL: http://localhost:8000/api/products/
Django Version: 3.0.4
Exception Type: AssertionError
Exception Value:
Class ProductSerializer missing "Meta.model" attribute
Exception Location: c:\dev\django-paystack\env\lib\site-packages\rest_framework\serializers.py in get_fields, line 1020
Python Executable: c:\dev\django-paystack\env\Scripts\python.exe
Python Version: 3.7.1
Python Path:
['c:\\dev\\django-paystack',
'c:\\dev\\django-paystack\\env\\Scripts\\python37.zip',
'C:\\Users\\Romeo\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
'C:\\Users\\Romeo\\AppData\\Local\\Programs\\Python\\Python37\\lib',
'C:\\Users\\Romeo\\AppData\\Local\\Programs\\Python\\Python37',
'c:\\dev\\django-paystack\\env',
'c:\\dev\\django-paystack\\env\\lib\\site-packages']
Server time: Wed, 29 Jul 2020 14:43:24 +0000
from django.shortcuts import render
from rest_framework import viewsets, generics
from rest_framework.response import Response
from .models import Product
from .serializer import ProductSerializer
class ProductsViewSet(viewsets.ViewSet):
"""List products viewset"""
def list(self, request):
queryset = Product.objects.all()
serializer = ProductSerializer(queryset, many=True)
return Response(serializer.data)
from django.db import models
class Product(models.Model):
"""Product items"""
name = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
image = models.FileField(upload_to="uploads/%Y/%m/%d", null=True, blank=True)
price = models.FloatField(null=True, blank=True)
def __str__(self):
return self.name
class Order(models.Model):
"""Order for product item"""
product = models.ForeignKey(
Product, max_length=200, blank=True, on_delete=models.DO_NOTHING
)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.product.name
from rest_framework import serializers
from .models import Product, Order
class ProductSerializer(serializers.ModelSerializer):
"""Products model serializer"""
class Meta:
model: Product
fields: "__all__"
class OrderSerializer(serializers.ModelSerializer):
"""Order model serializer"""
class Meta:
model: Order
fields: "__all__"
Upvotes: 1
Views: 1179
Reputation: 5857
The syntax with a :
is not correct when defining Meta
, use =
, as follows:
class Meta:
model = Product
fields = "__all__"
Upvotes: 1