简体   繁体   中英

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. 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)

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

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;

You can use filter and only to get desired result.

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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