python - Django:如何在模型中不相关的 2 个表之间进行查询?
问题描述
我有 2 个不相关的模型(也许应该......)
我需要进行查询,根据 asp_sto_loc=asp_par_loc选择我的表Stock WITH 相关行的所有记录
类似 SQL 的东西:
select * from pha_asp_sto left join pha_asp_par on pha_asp_par.asp_par_loc=asp_sto_loc;
如何在 Django 中进行这样的查询?
模型.py
class Stock(models.Model):
asp_sto_cle = models.AutoField(primary_key=True)
asp_sto_loc = models.CharField("Site concerned", max_length=10, null=True, blank=True)
asp_sto_pla = models.IntegerField("Quantity of placebos available", null=True, blank=True,)
asp_sto_asp = models.IntegerField("Quantity of aspirin available", null=True, blank=True)
class Parametrage(models.Model):
asp_par_cle = models.AutoField(primary_key=True)
asp_par_loc = models.CharField("Site concerned by settings", max_length=10, null=True, blank=True)
asp_par_ale = models.IntegerField("Site alert value for the site", null=True, blank=True,)
asp_par_con = models.IntegerField("Site confort value for the site", null=True, blank=True,)
解决方案
也许额外的这将适用于您的情况:
Stock.objects.extra(
select={
field_name: f'SELECT {field_name} FROM Parametrage WHERE Parametrage.asp_par_loc = Stock.asp_sto_loc' for field_name in Parametrage._meta.fields if field_name != 'id'
}
)
推荐阅读
- python - “视图”包中模块中的Django视图,按模块名称调用 - 命名空间问题
- django - 有没有办法在模型字段上调用函数?
- python - 尝试下标包含无值的元组列会导致“NoneType”对象不可下标
- r - 如何为 hist 中分布的头部和尾部分配不同的 bin 大小?
- amazon-web-services - 如何在 GraphQL 中正确地使用参数进行订阅?
- javascript - HTML 按顺序定位消息
- javascript - 无法加载 wasm 应用程序
- scala - 无论如何,在 Scala 中,是否可以从更通用的类型中获取 Singleton 类型的东西?
- reactjs - 如何更新组件之间的反应上下文?
- integer - 将 GeoTiFF 转换为整数栅格