2015-10-15 44 views
0

TL;博士:阅读最后一段的web2py:DAL找到()不工作

我有这应该在一个列表返回三个row对象的功能。和行对象如下:

  • 从表行mining
  • 属于当前savestate
  • process是1,2或3,分别为在列表中的三个成员
  • 那些最大的一个finish_date

采矿与savestates没有直接关系,所以我必须跟踪相关ct透过名为turn的表进行投资。关系如下:savestate 1:n转1:1挖矿。

这是我到目前为止有:

def get_latest_minings(save_id): 
    return_list = [] 
    #get all turn.ids that belong to this savestate: 
    savestate_turns = [s.id for s in db(db.turn.savestate_id == save_id).select(db.turn.id)] 
    #get all minings that belong to these turns: 
    save_minings = db(db.mining.turn_id.belongs(savestate_turns)).select() 
    #loop to get three objects: 
    for i in range(1,4): 
     #from save_minings, get all minings, whose process is i: 
     line_minings = save_minings.find(lambda row: row.process == i) 
     #initialize loop variables: 
     latest_date = 0 
     latest = None 
     #loop to find the biggest finish_date: 
     for m in line_minings: 
      if m.finish_date > latest_date: 
       latest_date = m.finish_date 
       latest = m 
     #add the row with the biggest finish_date to the list: 
     return_list.append(latest) 
    #return locals() for testing purposes: 
    return locals() 
    #actual return: 
    #return return_list 

以此为目的但不起作用。这是它返回:

https://www.dropbox.com/s/ns6mq9414vw25s9/get_latest_minings.png?dl=0

我遇到了一些独立的测试和我发现是与线问题:line_minings = save_minings.find(lambda row: row.process == i)。其他所有生产线都应该如此。这里有什么问题?另一个问题:可以优化更多吗?我特别好奇寻找正确的投资者。

回答

1
  1. 关于第一个问题What is wrong here?
    难道过程的字段类型设置为stringtext或任何其他比integer

  2. 您的第二个问题can this be optimized more?:是的。大概。

没有你的代码手头的休息,这里有一个镜头:

def get_latest_minings(save_id): 
    # from the minings that belong to this savestate: 
    query = (db.mining.turn_id == db.turn.id) & (db.turn.savestate_id == save_id) 

    # [optional] if you want to restrict the process ids only to be 1,2 or 3. 
    # given your output, you only have 1 and 2 so it would be useless 
    # again, mind the datatype, don't compare strings to integers. 
    # but for completion, i'll stick to your original functionality 
    query &= (db.mining.process.belongs([1,2,3])) 

    # get the latest finish date per mining process 
    maxdate = db.mining.finish_date.max() 
    save_minings = db(query).select(maxdate, db.mining.process, groupby=db.mining.process) 

    # create a lookup structure with processid as key 
    last_date_lookup = {row.mining.process:row[maxdate] for row in save_minings} 
    # query the lookup structure per process id or None if not available 
    return [last_date_lookup.get(pid) for pid in range(1,4)] 

这是未经测试,当然,甚至不会分析或什么,但我希望它能帮助。

还记得可能有关于web2py的DAL无法找到某个字段的错误。我注意到当查询连接的表时,需要以不同的方式查询返回的行。大多数情况下,您可以在row.mining.process中看到使用表名的位置,而不是row.process,这在仅查询mining表时非常适用。