How to Serialize more data from more than one table in Django Rest-framework

Asked

Viewed 509 times

0

Speak People! I am the following problem:

I have a buy-and-sell schedule:

class SalesOrBuy(models.Model):
    client = models.ForeignKey(Client, null=True, on_delete=models.CASCADE)
    mode   = models.IntegerField(choices = [(0,'VENDA'), (1,'COMPRA')])
    status = models.IntegerField(choices = STATUS_CHOICES, default='PENDENTE')
    date   = models.DateField(auto_now=False, auto_now_add=False)
    off   = models.DecimalField(max_digits=3, decimal_places=2, default=0)
    amount = models.DecimalField(max_digits=8, default=0, decimal_places=2)

and one of Cart Items that receive Pk(sbid) from Purchase and Sales as Forenig Key:

class CartItem(models.Model):
    product = models.ForeignKey(Product, null=True, on_delete=models.PROTECT)
    qtd = models.IntegerField( default=0, validators=[ MinValueValidator(0) ] )
    sbid = models.ForeignKey(SalesOrBuy, null=True, blank=True, on_delete=models.CASCADE)
    svid = models.ForeignKey(Service, null=True, blank=True ,on_delete=models.CASCADE)
    op_type = models.IntegerField(choices = [(0,'COMPVEND'), (1,'ITEM'), (2,'MATERIAL')], default=0)

Now I’m trying to create a Rest api with Django-Restframework, but to reduce the number of requests I would like to pass only a json containing the information from the Salesorbuy table as well as from the Cartitem table as follows:


{
    "client": 1,
    "mode": 1,
    "status": 0,
    "date": "2019-04-07",
    "off": "1.11",
    "amount": "6.00",
    "cart":[[1,5],[3,2]]
}

where "Cart" would be a list list containing the product id and quantity of the product.

I saw by Doc Framework and managed to make the traditional CRUD of both tables:

py serializers.

class SaleOrBuySerializer(serializers.ModelSerializer):
    class Meta:
        model = SalesOrBuy
        fields = [
            'client',
            'mode',
            'status',
            'date',
            'off',
            'amount'
        ]



class CartItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = SalesOrBuy
        fields = [
            'product',
            'qtd',
            'sbid',
            'svid',
            'op_type',
        ]

py views.

class SaleOrBuyListView(generics.ListCreateAPIView):
    serializer_class = SaleOrBuySerializer

    def get_queryset(self):
        return SalesOrBuy.objects.all()


class SaleOrBuyRudView(generics.RetrieveUpdateDestroyAPIView):
    lookup_field = 'pk'

    serializer_class = SaleOrBuySerializer

    def get_queryset(self):
        return SalesOrBuy.objects.all()

only this way I would have to do many requests to mount the data in the frontend

1 answer

1


First name for your relationship to make it easier to understand:

class CartItem(models.Model):
    product = models.ForeignKey(Product, null=True, on_delete=models.PROTECT)
    qtd = models.IntegerField( default=0, validators=[ MinValueValidator(0) ] )
    sbid = models.ForeignKey(SalesOrBuy, null=True, blank=True, on_delete=models.CASCADE, related_name="cart")
    svid = models.ForeignKey(Service, null=True, blank=True ,on_delete=models.CASCADE)
    op_type = models.IntegerField(choices = [(0,'COMPVEND'), (1,'ITEM'), (2,'MATERIAL')], default=0)

You will need to create a Serializer of Product. Then do the vicules as follows:

class ProductSerializer(serializers.ModelSerializer):
    ...

class CartItemSerializer(serializers.ModelSerializer):

    product = ProductSerializer(many=True, read_only=False)

    class Meta:
        model = SalesOrBuy
        fields = [
            'product',
            'qtd',
            'sbid',
            'svid',
            'op_type',
        ]

class SaleOrBuySerializer(serializers.ModelSerializer):

    cart = CartItemSerializer(many=True)

    class Meta:
        model = SalesOrBuy
        fields = [
            'client',
            'mode',
            'status',
            'date',
            'off',
            'amount',
            "cart" # Nome do relacionamento que vc deu no model
        ]

Reference for studies here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.