如何使用双连接条件连接三个多对多模型

时间:2011-05-19 22:57:38

标签: django django-models

我想执行三个模型/表的查询:

-- get all items that don't have a status for this member
SELECT  i.*
FROM
 mock_item i
 LEFT JOIN mock_itemstatusmember ism ON i.id = ism.item_id AND ism.member_id = 2

WHERE
 ism.id IS NULL

以下是我的模型的外观:

from django.db import models

# think status as a status
class Member(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)

class Status(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    no = models.SmallIntegerField()

class Item(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    status = models.ManyToManyField(Status, through='ItemStatusMember')
    member = models.ManyToManyField(Member, through='ItemStatusMember')    


class ItemStatusMember(models.Model):
    """
    Table that keeps job statuss information for a user.
    Tides Items with Members with Statuss
    """
    id = models.AutoField(primary_key=True)
    member = models.ForeignKey(Member)
    status = models.ForeignKey(Status)
    item = models.ForeignKey(Item)

他们的数据库样本数据:

mysql> select *  from mock_member;
+----+--------+
| id | name   |
+----+--------+
|  1 | Stefan |
|  2 | Alex   |
|  3 | Diana  |
+----+--------+
3 rows in set (0.00 sec)

mysql> select *  from mock_status;
+----+---------+----+
| id | name    | no |
+----+---------+----+
|  1 | Pending |  1 |
|  2 | Success |  2 |
+----+---------+----+
2 rows in set (0.00 sec)

mysql> select *  from mock_item;
+----+----------------+
| id | name           |
+----+----------------+
|  1 | My first item  |
|  2 | My second item |
|  3 | My third item  |
+----+----------------+
3 rows in set (0.00 sec)

mysql> select *  from mock_itemstatusmember;
+----+-----------+-----------+---------+
| id | status_id | member_id | item_id |
+----+-----------+-----------+---------+
|  1 |         1 |         1 |       1 |
|  2 |         2 |         1 |       2 |
|  3 |         1 |         2 |       1 |
+----+-----------+-----------+---------+
3 rows in set (0.00 sec)

我需要使用ORM,而不是使用ORM中的原始SQL查询工具来获取所有没有该成员状态的项目。

问题开头的SQL查询执行此操作,因此拥有

非常重要
AND ism.member_id = 2

条件作为左连接部分的第二个条件,而不是移入where,我知道该怎么做。

1 个答案:

答案 0 :(得分:1)

from django.db.models import Q    
Item.objects.filter(~Q(member__id=2))