atropa belladona
atropa belladona

Reputation: 524

Getting ID of the Category from ManyToManyField Instead of title attached to Category Model

I don't want id to serialized in the api when i fetch data of the product model, but just want attached title to the category model For now this is how the data look like.

GET /api/v1/catalogue/1/
{
"id": 1,
"name": "iPhone 13",
"image": "/mediafiles/products/2022/01/30/product-placeholder.png",
"timestamp": "2022-01-30T22:52:11.259452+05:00",
"updated": "2022-01-30T22:52:11.259452+05:00",
"variant": "8gb Ram / 256 Storage",
"product_brand": 1,
"product_category": [
1
]
}

As u see the product_category giving me the set of id's instead of title.

these are the two models

class Category(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(upload_to='Categories/%Y/%m/%d', null=True, blank=True,
                              default='/category-placeholder.png')
    ...

    

class Product(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='products/%Y/%m/%d', null=True, blank=True,
                              default='/product-placeholder.png')
    product_category = models.ManyToManyField(
        Category, related_name="product_category")
    product_brand = models.ForeignKey(
        Brand, on_delete=models.CASCADE, related_name="product_brand"
    )
    ...

edit: Related serializer added.

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

So I don't know how to put title inside product_category set instead of there id's

Upvotes: 0

Views: 55

Answers (1)

adshin21
adshin21

Reputation: 188

There is two options doing the same,

  1. Make a separate serializer for Category and use the same into ProductSerializer

Eg.

class CategorySerializer:
    class Meta:
        model = Category
        fields = '__all__

then

class ProductSerializer(serializers.ModelSerializer):
    product_category = CategorySerializer(many=True, read_only=True)
    class Meta:
        model = Product
        fields = '__all__'
  1. Use method SerializerMethodField - link
class ProductSerializer(serializers.ModelSerializer):
    product_category = serializers.SerializerMethodField()
    class Meta:
        model = Product
        fields = '__all__'

    def get_product_category(self, obj):
         return obj.product_category.values_list("title")

Upvotes: 1

Related Questions