Django 模型:获取元素,将它们作为外键存在于另一个 table

Django Models : Get elements considering their presence as a foreign key in another table

我很难准确解释我想用 Django 模型做什么,但我设法写下了 MySQL 个查询。

from django.db import models
from django.contrib.auth.models import User

class Item(models.Model):
    id = models.PositiveIntegerField(unique=True, primary_key=True)
    something = models.CharField(max_length=100)

class OwnedItem(models.Model):
    id = models.PositiveIntegerField(unique=True, primary_key=True)
    item = models.ForeignKey(Item)
    owner = models.ForeignKey(User)
    isWorking = models.BooleanField(default=False)

MySQL 版本:http://pastebin.com/kyiMCJfm

获取 John 拥有的所有可用的项目:

SELECT i.*, o.Owner, o.isWorking FROM Item as i JOIN OwnedItem AS o WHERE o.Item = i.Id AND o.Owner = 'john' AND o.isWorking=1 GROUP BY i.id

获取 John 不拥有或不工作的所有项目:

SELECT * FROM Item WHERE id NOT IN (SELECT Item FROM OwnedItem WHERE owner='john' AND isWorking=1)

如何使用 Django 模型语法编写这些查询?

第一个

Item.objects.filter(itemowned__owner__username__iexact="john", 
                   itemowned__isworking=True)

对于第 2 个,您需要使用 Q 个对象

Item.objects.exclude(Q(itemowned__owner__username__iexact="john") |
                    Q(itemowned__isworking=True))