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)

HTH

于 2012-05-18T12:26:11.683 に答える
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 に答える
0

これはdjangoコードだと思います。

その場合、構文よりも大きな問題があります。表示されているコードのビットは完全なテーブルを取得し、それを Python コードでフィルタリングします。あなたはそれをすべきではありません。

問題は、SQL テーブル内の位置を意味のあるものとして使用することです。あなたがすべきことは、LVオブジェクト内にバージョン番号を明示的に持つことです。

于 2012-05-18T12:37:30.087 に答える