简体   繁体   English

Django等效于使用INNER JOIN的SQL查询-子句

[英]Django equivalent for SQL query using INNER JOIN -clause

I would like to know the django equivalent for the SQL-query that uses the INNER JOIN -clause. 我想知道使用INNER JOIN -clause的SQL查询的django等效项。 I have two models that are linked with ForeignKey. 我有两个与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)

I want to get fields from the Request-table which has the "item_is_locked" value set to false in Item-table 我想从请求表中获取字段,该表的Item表中的“ item_is_locked”值设置为false

If using SQL-query I would use this: 如果使用SQL查询,我将使用以下代码:

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

You can use filter and only to get desired result. 您可以使用filter并且only获得所需的结果。

Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM