1

假设我们有一个基本模型。

class Log(models.Model):
    key = fields.BigInteger()
    calldate = fields.DateTimeField()
    followupdate = fields.DateTimeField()

可以为同一个键设置多个 followupdates。我想做的是在列表中显示最近(按通话日期)安排的后续行动。

在我看来,我有以下几点:

# views.py

def callbacks(request):
    """ get objects where a followupdate has been specified """
    q = Log.objects.filter(followupdate__isnull = False).order_by("-calldate")

    """ deduplicate key so only most recently scheduled followupdate show """ 
    newresults = []
    seen_key = []   
    for result in q:
        if result.key not in seen_key:
            seen_key.append(result.key)
            newresults.append(result)

    results = newresults
    """ What I want to do is equivalent to results.order_by("followupdate") """
    """ But since it's a dictionary now and not a queryset, I can't """
    return render_to_response('callbacks.html', {"callbacks":results})

我需要帮助的是results通过 key重新排序字典 , followupdate。在每个字典中都有一个这样的键:'followupdate': datetime.date(2013, 3, 25)这是我需要重新排序的。

4

2 回答 2

2

.sort()似乎像这样工作-

l.sort(key=lambda item:item['followupdate'], reverse=True)

测试用例 -

>>> l = [{'followupdate': datetime.date(2013, 3, 25)}, {'followupdate': datetime.date(2013, 3, 24)}, {'followupdate': datetime.date(2013, 3, 29)}]
>>> l
[{'followupdate': datetime.date(2013, 3, 25)}, {'followupdate': datetime.date(2013, 3, 24)}, {'followupdate': datetime.date(2013, 3, 29)}]
>>> l.sort(key=lambda item:item['followupdate'], reverse=True)
>>> l
[{'followupdate': datetime.date(2013, 3, 29)}, {'followupdate': datetime.date(2013, 3, 25)}, {'followupdate': datetime.date(2013, 3, 24)}]
于 2013-03-25T19:34:49.157 回答
2

您应该让数据库进行重复数据删除,而不是从数据库中获取记录仅在 Python 中丢弃它们,这是浪费时间和带宽。

Django 的对象-关系映射不能做到这一点,但你可以在 SQL 中这样做:

SELECT L1.*
FROM myapp_log AS L1,
     (SELECT MAX(date) AS maxdate, `key`
      FROM myapp_log GROUP BY `key`) as L2
WHERE L1.date = L2.maxdate
  AND L1.`key` = L2.`key`
  AND L1.followupdate IS NOT NULL
ORDER BY L1.date DESCENDING

(字段名称key需要引用,因为它是 SQL 关键字。)

raw()然后,您可以使用方法从 Django 运行此查询,如下所示:

sql = '''
    SELECT L1.* FROM myapp_log AS L1,
    # and so on (see above)
    '''
q = Log.objects.raw(sql)
于 2013-03-25T19:56:19.780 回答