Django rest Framework - Custom Json Response

Viewed 253

i'm new into Python and Django Rest Framework. I'm trying to return a "custom" json response but i can't figure it out how to achieve the result i want.

I'm building an Ecommerce api where i have "boxes" with "products", this BoxProduct model was created because i need a relation between Products and Boxes, but the same product can be in different boxes, ex: Product.id=1 is in box_id=2 and box_id=4. That's why i created this middle model.

BoxProduct Model

    class BoxProduct(models.Model):
        product = models.ForeignKey(Product, on_delete=models.DO_NOTHING, null=True, related_name='box_product')
        box = models.ForeignKey(Box, on_delete=models.DO_NOTHING, null=True, related_name='box_box')
        product_price = models.DecimalField(max_digits=8, decimal_places=0, null=True, blank=True)

I tried to link the serializers of Product and Box but i didn't get wat i want.

BoxProduct Serializer

class BoxProductSerializer(serializers.ModelSerializer):
    product = ProductSerializer(many=True, read_only=True)
    box = BoxSerializer()

    class Meta:
        model = BoxProduct
        fields=['box', 'product']

The idea is to have a returned json like this:

{
    "box_id": 232323,
    "box_name": "Box name Test",
    "products": [
      {
        "name": "product name 1",
        "type": "product_type"
      },
      {
        "name": "product name 2",
        "type": "product_type"
      },
      {
        "name": "product name 3",
        "type": "product_type"
      }
    ]
  }

What would be the best approach to do this?

Thanks for your help!

1 Answers

It seems like you want to get a box and products inside this box. For that you should use BoxSerializer, not BoxProductSerializer:

# 1. Add 'products' method to Box model:
class Box(models.Model):
  ...

  def products(self):
    return Product.objects.filter(boxproduct_set__pk__in=self.boxproduct_set)

# 2. Your BoxSerializer should look like this:
class BoxSerializer(serializers.ModelSerializer):
  products = ProductSerializer(many=True, read_only=True)

  class Meta:
    model = Box
    fields = (..., 'products')

Related