我有以下模型:
class Node(models.Model):
name = models.CharField(max_length=128)
user = models.Foreignkey(User)
class Meta:
db_table = 'node'
class Thing(models.Model):
user = models.ForeignKey(User)
begin_time = models.DateTimeField()
node = models.ManyToManyField(Course)
class Meta:
db_table = 'thing'
class NodeLog(models.Model):
actor = models.ForeignKey(User)
node = models.ForeignKey(Node, related_name='nodelog_node')
action_time = models.DateTimeField()
result = models.CharField(max_length=128)
class Meta:
db_table = 'node_log'
以下数据如下:
table: node
+----+-------+---------+
| id | name | user_id |
+----+-------+---------+
| 1 | node1 | 101 |
+----+-------+---------+
| 2 | node2 | 102 |
+----+-------+---------+
table: thing
+----+---------+---------------------+
| id | user_id | begin_time |
+----+---------+---------------------+
| 1 | 1 | 2015-01-01 03:00:00 |
+----+---------+---------------------+
table: thing_node
+----+----------+---------+
| id | thing_id | node_id |
+----+----------+---------+
| 1 | 1 | 1 |
+----+---------+----------+
| 2 | 1 | 2 |
+----+---------+----------+
table: node_log
+----+----------+---------+------------------------------+
| id | actor_id | node_id | action_time | result |
+----+----------+---------+------------------------------+
| 1 | 101 | 1 |2015-01-01 01:00:00 | agree |
| 2 | 102 | 2 |2015-01-01 02:00:00 | agree |
| 3 | 101 | 1 |2015-01-01 04:00:00 | agree |
+----+----------+---------+--------------------+---------+
如果有人同意并且他的action_time大于begin_time,他再也不能同意,所以我确实排除了这样:
Thing.objects.filter(***).exclude(node__nodelog_node__action_time__gt=F('begin_time'), node__nodelog_node__actor=request.user)
request.user是102,结果是[]。
的结果Thing.objects.filter(***)
是对的,有什么建议吗?谢谢!
答案 0 :(得分:0)
我认为问题可能在于排除的行为不像过滤器。在排除中,条件不需要保持在一起(即不是和/或)
filter()对跨越多值的查询的行为 如上所述,关系不是等效地实现的 排除()。相反,单个exclude()调用中的条件不会 必须指同一个项目。例如,以下查询 将排除包含两个带有“列侬”的条目的博客 2008年发布的标题和条目:
Blog.objects.exclude( entry__headline__contains='Lennon', entry__pub_date__year=2008, ) However, unlike the behavior when using filter(), this will not limit blogs based on entries that satisfying both conditions. In order
这样做,即选择所有不包含条目的博客 与2008年出版的“列侬”一起出版,你需要制作 两个问题:
Blog.objects.exclude( entry=Entry.objects.filter( headline__contains='Lennon', pub_date__year=2008, ), )