索引,循环和使事情看起来更清洁

时间:2012-05-18 12:10:01

标签: python django

我有许多代表不同版本字母的对象。其中一些版本已经打​​印(时间戳记)。如果打印了一封字母(包含所有版本),我需要获得最后打印版本的时间戳(轻松完成),然后是最后打印版本的版本号(目前我的代码看起来像C ++ {shiver} )。

那我该如何让这个看起来更加pythonic(更干净)

try:
    # get the lastest letter version that has been printed
    lv_temp = LV.objects.filter(letter=letter.id,printed_last__isnull=False).latest('id')
    # get the id's of all the letter versions for a particular letter
    lv_temp2 = LV.objects.filter(letter=letter.id).order_by('id')
    lv_temp4 = []
    # get all the letter version for a particular letter
    for lv_temp3 in lv_temp2:
        lv_temp4.append(lv_temp3.id)
    # get an array of the indexes and the pks
    for i,v in enumerate(lv_temp4) :
        # if the pk of the last printed version is the same one as in the loop...
        if lv_temp.id == v :
            # ...save the index as the version number
            lv_printed_ver = i
    lv_printed = lv_temp.printed_last
except ObjectDoesNotExist:
    lv_printed = None
    lv_printed_ver = None

(我使用了lv_temp...因为我生气了多少次我必须传递的东西)

3 个答案:

答案 0 :(得分:6)

生成id列表的更加pythonic方式是列表理解,替换

lv_temp2 = LV.objects.all().order_by('id')
lv_temp4 = []
for lv_temp3 in lv_temp2:
    lv_temp4.append(lv_temp3.id)

lv_temp4 = [i.id for i in LV.objects.all().order_by('id')]

然后,假设我正确理解您的代码并且您正在列表中查找与id匹配的索引,您可以这样做:

lv_printed_ver = lv_temp4.index(lv_temp.id)

HTH

答案 1 :(得分:0)

我猜这是一些django代码。

在这种情况下,你遇到的问题比语法更大:你向我们展示的代码位获得一个完整的表,然后用python代码过滤它。你不应该这样做。

您的问题是您使用sql表中的位置作为有意义的东西。您应该做的是在LV对象中明确显示版本号。

答案 2 :(得分:0)

我说这一切都错了。而不是:

# get the last printed letter version for a letter
# get all the letter versions for a letter
# loop over all the letter versions for a letter and extract their id
# loop over the letter versions id's and compare them to the id of the...
#     ... last printed letter version
# if they match save the position in the loop as the version number

应该想到这样:

# get the last printed letter version for a letter
# count all the letter versions for a particular letter where their...
#    ... id's are less then the id of the last printed letter version...
#    ... and use this as the version number

这种不同的思维方式让我最终得到:

try:
    # get the lastest letter version that has been printed
    lv_temp = LV.objects.filter(letter=letter.id,printed_last__isnull=False).latest('id')
    # count the number of letter versions for a particular letter whos...
    #      ... id is less then the id of the last printed letter version
    lv_printed_ver = LV.objects.filter(letter=letter.id,id__lte=lv_temp.id).count()
    lv_printed = lv_temp.printed_last
except ObjectDoesNotExist:
    lv_printed = None
    lv_printed_ver = None