1

我有许多代表不同版本字母的对象。其中一些版本已印刷(加盖时间戳)。如果已经打印了一封信(及其所有版本),我需要获取最后一个打印版本的时间戳(很容易完成),然后是最后一个打印版本的版本号(目前使我的代码看起来像 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...是因为我生气了多少次我不得不传递东西)

4

3 回答 3

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)

高温高压

于 2012-05-18T12:26:11.683 回答
0

我猜这是一些 django 代码。

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

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

于 2012-05-18T12:37:30.087 回答
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
于 2012-05-18T13:39:48.603 回答