# models.py
# 基金庫:基金代碼,基金名稱
class Fund(models.Model):
code = models.CharField(max_length=20, unique=True, primary_key=True)
name = models.CharField(max_length=250, blank=True, default='')
# 基金净值庫:基金代碼,净值日期,净值,增長率,備注
class FundData(models.Model):
fund = models.ForeignKey(Fund, on_delete=models.CASCADE)
net_worth_date = models.DateField()
net_worth = models.DecimalField(max_digits=12, decimal_places=4)
growth_rate = models.DecimalField(max_digits=10, decimal_places=4)
remark = models.TextField(blank=True)
假設,添加了基金代碼為100001的基金,並添加該基金的净值歷史數據,一些查詢的方法如下:
f = Fund.objects.filter(code='100001')
# 獲取所有的基金净值數據
f.funddata_set.all()
# 獲取指定日期的基金數據
fd = f.funddata_set.filter(net_worth_date='2022-05-01')
# or
# FundData.objects.filter(fund=f, net_worth_date="2022-05-01")
# FundData.objects.filter(fund_id=f.code, net_worth_date="2022-05-01")
# 判斷上述的查詢的結果:True返回List,False則沒有找到
fd.exists()
# 獲取數據庫内最新日期的基金净值數據
f.funddata_set.all().order_by('-net_worth_date').first()
# or
# FundData.objects.filter(fund=f1).order_by('-net_worth_date').first()
# 獲取最近7天的基金數據
f.funddata_set.all().order_by('-net_worth_date')[:7]
# or
# FundData.objects.filter(fund=f1).order_by('-net_worth_date').first()