Django等效于使用INNER JOIN的SQL查询-子句 [英] Django equivalent for SQL query using INNER JOIN -clause

查看:92
本文介绍了Django等效于使用INNER JOIN的SQL查询-子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用INNER JOIN -clause的SQL查询的django等效项。我有两个与ForeignKey链接的模型。

I would like to know the django equivalent for the SQL-query that uses the INNER JOIN -clause. I have two models that are linked with ForeignKey.

class Item(models.Model):
    item_name = models.CharField(max_length=100)
    item_is_locked = models.BooleanField(default=False)

class Request(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    item_owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    message_body = models.TextField(max_length=5000, null=True)

我想从Request-table中获取字段,该字段的Item表中的 item_is_locked值设置为false

I want to get fields from the Request-table which has the "item_is_locked" value set to false in Item-table

如果使用SQL查询,我将使用以下命令:

If using SQL-query I would use this:

SELECT Request.item_owner,Request.message_body FROM Request INNER JOIN Item ON Request.item_id=Item.id AND Item.item_is_locked=False;


推荐答案

您可以使用 过滤器 only 以获得理想的结果。

You can use filter and only to get desired result.

尝试:

Request.objects.filter(item__item_is_locked=False).only('item_owner', 'message_body')

这篇关于Django等效于使用INNER JOIN的SQL查询-子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆