How to configure serializer and/or models?

Dear Community, I need an assistance.

I have a simple structure like:
Scheme

Models are:

class Store(models.Model):
    name = models.CharField(max_length=50, unique=True, blank=False)
    delivery_cost = models.DecimalField(max_digits=11, decimal_places=2, blank=False)

class Product(models.Model):
    name = models.CharField(max_length=50, unique=True, blank=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True)
    description = models.TextField(blank=False)

class ProductStore(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    store = models.ForeignKey(Store, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(blank=False)
    price = models.DecimalField(max_digits=11, decimal_places=2, blank=False)

What I need is to get serializer output like:

Store_1:
   Product_1:
      some parameters
   Product_2:
      some parameters
....
Store X:
   Product_1:
      some parameters
   Product_2:
      some parameters

I cannot get such structure when I’m using serializer for common model (ProductStore). I tried to access through the Store model serializer but it does not have back relation from ProductStore to Store. I tried to use related_name property in ProductStore but it returns only one field instead of whole model, of course.

Tried to add ‘product’ field to Store model linked to Product model and use in StoreSerializer something like:

class StoreSerializer(serializers.ModelSerializer)
    product = ProductSerializer()
    class Meta:
       model = Store
       fields = ('id', 'name', 'delivery_cost', 'product')

did not work because there’s no direct logical connection between Store and Product defining which product is available in the particular store.

How can I get whole structure in such case?

I’ve made some lame decision using two additional relations which collect serializer for me in required way but it’s too complex decision, I’m pretty sure there’s an easier way.

Please assist, totally stucked.

You can user SerializerMethodField for this

class StoreSerializer(serializers.ModelSerializer)
    product = ProductSerializer()
    field_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
       model = Store
       fields = ('id', 'name', 'delivery_cost', 'product', 'field_name')

    def get_field_name(self, obj):
        ....
        return ..
1 Like

Yeaaah! Thank you, Sir!
You really made my day :slight_smile: