Django通过表连接即使不匹配

5cg8jx4n  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(98)

我开始使用Django,但我只是一个初学者。我对Django Queries有一个问题,尽管我在网上做了很多研究,但我还没有找到任何可以帮助我的答案。

Models.py:

class Articles(models.Model):
     ID = models.AutoField(primary_key=True)
     description = models.TextField()
     price = MoneyField(blank=True, null=True, decimal_places=2, max_digits=8, default_currency='EUR')
     class Meta:
        ordering = ('description',)
     def __str__(self):
         return self.description

class Interventions(models.Model):
     ID = models.AutoField(primary_key=True)
     start_date = models.DateField()
     description = models.TextField()
     Articles_ID = models.ManyToManyField(Articles, through="Detail", blank=True)

class Detail(models.Model):
     ID = models.AutoField(primary_key=True)
     article_id = models.ForeignKey(articles, on_delete = models.CASCADE)
     Intervention_ID = models.ForeignKey(Interventions, on_delete = models.CASCADE)
     quantity = models.IntegerField(null=True, blank=True, default='1')

我希望能够创建一个查询,该查询获取“干预”模型的所有记录和“详细信息”表的所有记录。
问题是,如果进行了干预,但没有使用任何物品,则不显示干预本身。
我该怎么办?我尝试使用prefetch_related,但似乎不起作用。衷心感谢大家。
示例输出表:

w1jd8yoj

w1jd8yoj1#

你实际上是在寻找一个左连接,你可以使用.values()来指定所有的字段。

Interventions.objects.values(
    "ID", "start_date", "description", "Articles_ID__description", "detail__quantity"
)

该查询等效于此sql查询

SELECT "interventions"."id",
       "interventions"."start_date",
       "interventions"."description",
       "articles"."description",
       "detail"."quantity"
FROM   "interventions"
       LEFT OUTER JOIN "detail"
                    ON ( "interventions"."id" =
                       "detail"."intervention_id_id" )
       LEFT OUTER JOIN "articles"
                    ON ( "detail"."article_id_id" = "articles"."id" )

输出:

<QuerySet [
{'ID': 4, 'start_date': datetime.date(2023, 6, 8), 'description': 'Try number one', 'Articles_ID__description': 'Article1', 'detail__quantity': 3},
{'ID': 4, 'start_date': datetime.date(2023, 6, 8), 'description': 'Try number one', 'Articles_ID__description': 'Article2', 'detail__quantity': 8},
{'ID': 5, 'start_date': datetime.date(2023, 6, 8), 'description': 'try number two', 'Articles_ID__description': None, 'detail__quantity': None},
{'ID': 6, 'start_date': datetime.date(2023, 6, 8), 'description': 'try number three', 'Articles_ID__description': 'Article2', 'detail__quantity': 10},
{'ID': 6, 'start_date': datetime.date(2023, 6, 8), 'description': 'try number three', 'Articles_ID__description': 'Article4', 'detail__quantity': 27},
{'ID': 6, 'start_date': datetime.date(2023, 6, 8), 'description': 'try number three', 'Articles_ID__description': 'Article32', 'detail__quantity': 1}
]>

这种方法的一个缺点是Join并不懒惰。
如果要重命名字段,请使用F模型

相关问题