Reputation: 63
I recently started to learn django, so I am not even sure how to ask this question. I want to build an api and I am using django rest framework. Now I have two main models Product and Category.
class Category(models.Model):
id = models.CharField(max_length=100, primary_key=True)
name = models.CharField(max_length=100)
class Product(models.Model):
id = models.CharField(max_length=100, primary_key=True)
title = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.FloatField(default=0.0)
And I have some functions
@api_view(['GET'])
def productList(request):
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
@api_view(['POST'])
def addProduct(request):
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
All of these seems to works fine and I am getting a response from an api that looks something like this:
{id: "1", title: "banana", price: 3, category: "1"}
As you can see response does not include category name that I need. Can you please help me figure this out? Thank you
Upvotes: 0
Views: 200
Reputation: 1272
You can update the to_representation
method of your serializer, to include the name of the category, or to use a nested representation. If you'd like to return the name of the category:
class ProductSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
data = super().to_representation(instance)
data['category'] = instance.category.name
return data
and if you'd like to return a nested representation of the category, you could do something like:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name',)
class ProductSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
data = super().to_representation(instance)
data['category'] = CategorySerializer(instance.category).data
return data
Keep in mind that this is for the case where you're using the same serializer for both creating and listing the products, and where you're creating the product by receiving the category's id (write), while also wanting to send it as another representation.
Upvotes: 1