栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Django模型1對多的查詢用法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django模型1對多的查詢用法

# 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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/935062.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号