首页 > 解决方案 > 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,)

标签: pythondjangodjango-queryset

解决方案


也许额外的这将适用于您的情况:

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'
   }
)

推荐阅读