我有两个看起来像这样的模型:
class Node(models.Model):
user = models.ForeignKey(User, null=False)
name = models.CharField(max_length=50)
class Activation(models.Model):
node = models.ForeignKey(Node, null=False)
active = models.BooleanField(default=False)
datetime = models.DateTimeField(default=datetimeM.datetime.now)
激活表存储给定节点是否“活动”。因此,要确定节点是否处于活动状态,需要获取该节点的最新激活记录。
我正在试图弄清楚如何编写一个返回所有活动节点的django查询。
以下是一些示例数据
Node Table
id | name
--------------------
0 | andrew
1 | bill
2 | bob
Activation Table
id | nodeId | active | datetime
--------------------
0 | 0 | false | 01-01-2013:00:01:02
1 | 0 | true | 01-02-2013:00:01:02
2 | 0 | false | 01-03-2013:00:01:02
3 | 1 | false | 01-04-2013:00:01:02
4 | 0 | true | 01-05-2013:00:01:02
5 | 1 | true | 01-06-2013:00:01:02
6 | 2 | false | 01-07-2013:00:01:02
因此查询需要返回[node0,node1]
答案 0 :(得分:0)
class Node(models.Model):
user = models.ForeignKey(User, null=False)
name = models.CharField(max_length=50)
class Activation(models.Model):
node = models.ForeignKey(Node, null=False, related_name='activations')
active = models.BooleanField(default=False)
datetime = models.DateTimeField(default=datetimeM.datetime.now)
#latest activation record for that node:
try:
latest_activation = node.activations.latest('id')
except:
latest_activation = None
# Return all active notes:
all_active_notes = Node.objects.filter(activations__active=True)
更新: 检查这个问题我发布的是什么: Django reverse query by the last created object 也许这会对你有帮助。