hi I want in my products api
show the name of category instead of showing category id . I wrote a function to do that for me but I have this error:
AttributeError at /
'Product' object has no attribute 'get_category_display'
how do i can fix it?? there is my serializer and category and product models
serializers:
class ProductSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField()
category = serializers.SerializerMethodField()
class Meta:
model = Product
fields = ['id', 'category', 'name', 'slug', 'image_1',
'image_2', 'image_3', 'image_4', 'image_5',
'description', 'attribute', 'price', 'available', 'created', 'updated',
'popular', 'discount', 'comments']
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}
def get_comments(self, obj):
comments_qs = Comment.objects.filter_parents_by_object(obj).order_by('posted')
return CommentSerializer(comments_qs, many=True).data
def get_category(self, obj):
return obj.get_category_display()
models:
class Category(models.Model):
name = models.CharField(max_length=400)
def __str__(self):
return self.name
class Product(models.Model):
category = models.ManyToManyField(Category, related_name='products')
name = models.CharField(max_length=500)
slug = models.SlugField(max_length=500, allow_unicode=True, unique=True)
image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True)
description = models.TextField(null=True, blank=True)
attribute = models.JSONField(null=True, blank=True,
help_text='in this format: {"key" : "value", "key2" : "value2"}')
price = models.PositiveIntegerField()
discount = models.PositiveIntegerField(null=True, blank=True)
available = models.BooleanField(default=True)
comments = GenericRelation(Comment)
class Meta:
ordering = ('-created',)
def __str__(self):
return self.name
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…