Home > Enterprise >  Django rest framework: how can I serialize multiple table to get combine JSON output
Django rest framework: how can I serialize multiple table to get combine JSON output

Time:10-22

I am very new to django, any help highly appreciated. thanks in advance! Here is my code 'model.py'

class Stocks(models.Model):
ticker = models.CharField(max_length=30, primary_key=True, unique=True)
company_name = models.CharField(max_length=100, blank=True, null=True)
sector = models.CharField(max_length=50, blank=True, null=True)

class Meta:
    db_table = 'stocks'

def __str__(self):
    return "%s %s %s" % (self.ticker, self.company_name, self.sector)


class QuarterlyFinance(models.Model):
ticker = models.ForeignKey(Stocks, db_column='ticker',on_delete=models.CASCADE, 
                                  related_name='quarter_result', blank=True, null=True)
quarter_end = models.DateTimeField(blank=True, null=True)
total_revenue = models.FloatField(blank=True, null=True)
net_income = models.FloatField(blank=True, null=True)

class Meta:
    db_table = 'quarterly_finance'
    unique_together = (('ticker', 'quarter_end'),)

def __str__(self):
    return "%s %s %s %s" % (self.ticker, self.quarter_end, self.total_revenue, 
                            self.net_income)

serialize.py

class StocksSerialize(serializers.ModelSerializer):
    class Meta:
        model=Stocks
        fields="__all__"
        depth=1
    
class QuarterlyFinanceSerialize(serializers.ModelSerializer):
    class Meta:
        model=QuarterlyFinance
        fields=['quarter_end', 'total_revenue','net_income']
        depth=1

view.py

class DataClassView(APIView):
   
    def get(self, request, format=None):
    max_day = Advice.objects.latest('advice_date').advice_date
    max_day=max_day.strftime("%Y-%m-%d")

    qfinance = QuarterlyFinance.objects.filter(ticker='TCS')
    stk = Stocks.objects.filter(ticker='TCS')

    qfin_ser_obj = QuarterlyFinanceSerialize(qfinance, many=True)
    stock_ser_obj = StocksSerialize(stk, many=True)
    
    result = stock_ser_obj.data  qfin_ser_obj.data
    
    return Response(result)

I want to return JSON output like this:

{
  "ticker": "TCS",
  "company_name": "Tata Consultancy Services Ltd",
  "sector": "IT",
  "qtr_result": [
           {
              "quarter_end": "2021-06-30T04:00:00",
              "total_revenue": 454110000000,
              "net_income": 90080000000
           },
          {
              "quarter_end": "2021-03-31T04:00:00",
              "total_revenue": 437050000000,
              "net_income": 92460000000
          },
         {
               "quarter_end": "2020-12-31T05:00:00",
               "total_revenue": 420150000000,
               "net_income": 87010000000
         },
         {
               "quarter_end": "2020-09-30T04:00:00",
               "total_revenue": 401350000000,
               "net_income": 74750000000
          }
               ]
}

my code is working but I am getting data from both table in separate array within JSON. I want QuarterlyFinance data should be inside Stock table data as an array.

CodePudding user response:

class StocksSerialize(serializers.ModelSerializer):
    quarter_result = QuarterlyFinanceSerialize(read_only=True, many=True)
    class Meta:
        model=Stocks
        fields="__all__"
        depth=1
  • Related