How to Merge Two Model Serialisers in Django Rest Framework

I want to merge the results of two models. I have two models as below. First is Product and the other is ProductChannelListing

class Product(models.Model):
    name = models.CharField()
    category = models.ForeignKey()
    # has many other fields which I want in the response

class ProductChannelListing(models.Model):
    product = models.ForeignKey()
    channel = models.ForeignKey()
    is_visible = models.BooleanField()
    price = models.IntegerField()

I want the result in the following way.

{ "name": "ABC", "category": {}, "is_visible": true, "price": 200, ** }

I want make the query efficient query such that it should not make so many queries.

from .models import Product, ProductChannelListing

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

class ProductChannelListingSerializer(model.serializer):
   product = ProductSerializer(ready_only=True)
   class Meta:
    model: ProductChannelListing
    fields = '__all__'

Do the same for channel also, and u will get all fields visible at one viewpoint with serializer_class as ProductChannelListingSerializer.

Back to Top