我是django的新手,任何帮助都非常感谢。提前感谢!这是我的代码'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)
我想返回这样的JSON输出:
{
"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
}
]
}
我的代码是工作的,但我从两个表在JSON内的单独数组的数据。我想要的QuarterlyFinance数据应该在股票表数据作为一个数组。
class StocksSerialize(serializers.ModelSerializer):
quarter_result = QuarterlyFinanceSerialize(read_only=True, many=True)
class Meta:
model=Stocks
fields="__all__"
depth=1