从选项卡排序数据

2024-09-27 09:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个模块的新版本,我需要为此创建一个新的表,但是我面临着一个让我发疯的小问题。在

下面是我的相关python代码:

import psycopg2, sys, psycopg2.extras, time

order = 4419

try:
    con = psycopg2.connect(host='localhost', database='DB01', user='odoo', password='******')
cur = con.cursor()
po_lines = 'SELECT pos_order_line.id FROM public.pos_order_line, public.product_template ' \
           'WHERE pos_order_line.product_id = product_template.id AND  pos_order_line.order_id = %s '\
           'AND (product_template.pos_categ_id != 5 AND product_template.pos_categ_id != 6)' \
           'ORDER BY pos_order_line.id ASC'
po_lines2 = 'SELECT pos_order_line.id, pos_order_line.order_id, product_template.name, pos_order_line.qty, product_template.pos_categ_id ' \
            'FROM public.pos_order_line, public.product_template  ' \
            'WHERE pos_order_line.product_id = product_template.id AND  pos_order_line.id = %s ' \
            'ORDER BY pos_order_line.id ASC'

cur.execute(po_lines,[order]); fetch_lines = cur.fetchall()
dish = ''; instr = []; kot = 0; dp = 0
print fetch_lines
for line in fetch_lines:
    cur.execute(po_lines2, [line]); pos_lines = cur.fetchone()
    if pos_lines[2].startswith('#'):
        instr.insert(1, pos_lines[2][2:]); kot = 1
    elif pos_lines[2].startswith('----'):
        dp = 1
    else:
        dish = pos_lines[2]
        kot = 0; instr = []
        if dp == 1:
            instr.insert(0, '!SERVIR DEPOIS!'); dp = 0
    if dish != pos_lines[2]:
        print 'Ordem: ', order, ' - Prato:', dish, ' - Instr:', instr, 'qt: ', pos_lines[3],'kot: ', kot, 'dp status:', dp

except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)

finally:
    if con:
        con.close()

从一个查询开始:

^{pr2}$

恢复所有不以“#”或“---”开头的产品线(pos_line[2])需要放在变量“instr”上,直到变量“dish”更改。 所有行都被正确读取,因为如果我在所有if循环的末尾放一个print语句,我可以看到变量是如何填充的:

1 Ordem: 4419 - Prato: Crudo GR - Instr: [] qt: 1.0 kot: 0 dp status: 0

2 Ordem: 4419 - Prato: Salame e Grana GR - Instr: [] qt: 1.0 kot: 0 dp status: 0

3 Ordem: 4419 - Prato: Salame e Grana GR - Instr: [] qt: 1.0 kot: 0 dp status: 1

4 Ordem: 4419 - Prato: Nutella Ban GR - Instr: ['!SERVIR DEPOIS!'] qt: 1.0 kot: 0 dp status: 0

5 Ordem: 4419 - Prato: Nutella Ban GR - Instr: ['!SERVIR DEPOIS!', 'Cortar em dois'] qt: 1.0 kot: 0 dp status: 0

我对这些行进行了计算,只是为了说明问题所在:第2行和第4行应该隐藏起来,因为它们只是中间步骤。 那么我需要的结果应该是:

^{3}$

有人能温和地告诉我代码中的错误在哪里,以及如何放置正确的print语句吗? 请注意,我对Python比较陌生,请宽恕我。在

谢谢。在

编辑:根据梅林的提示,用更简单的方法解决。

梅林编写的代码对我来说很复杂,因为我有很多变体。我用更基本的方式重写了部分脚本。 在这个版本中,我将fetch的行还原为grab,并将temp表中产品之后所需的所有指令(#)添加到相应的行中。然后我再次颠倒这些行,检查产品前面是否有一行'---',并将其添加到相应的产品中,最后我写到了最后的表中。这个脚本读起来非常简单(对于像我这样的新手来说),并且避免使用“operator”模块,只需用[::-1]反转一个表。在

TableTemp = []; newTable = []; Instr = ''

for line in fetch_lines[::-1]:
    if line[2].startswith('#') or line[2].startswith('----'):
        if line[2].startswith('#'):
            Instr = line[2][2:]+' | '+ Instr
        if line[2].startswith('----'):
            TableTemp.append((line[0], line[1], line[2], '', line[3], line[4]))
    else:
        TableTemp.append((line[0],line[1],line[2], Instr, line[3], line[4]))
        Instr = ''

for line in TableTemp[::-1]:
    if line[2].startswith('----'):
        Instr = '!SERVIR DEPOIS! | '
    else:
        newTable.append((line[0],line[1],line[2], Instr+line[3][:-3], line[4], line[5]))
        Instr = ''

结果:

内部提取:

(13264, 4558, 'Funghi GR', Decimal('1.0'), 'Mesa 11')
(13265, 4558, '# + Champinhons', Decimal('1.0'), 'Mesa 11')
(13266, 4558, '# + Alface', Decimal('1.0'), 'Mesa 11')
(13267, 4558, '# - R\xc3\xbacola', Decimal('1.0'), 'Mesa 11')
(13268, 4558, 'Formaggi GR', Decimal('1.0'), 'Mesa 11')
(13269, 4558, '# Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13270, 4558, '---- servir depois ----', Decimal('1.0'), 'Mesa 11')
(13271, 4558, 'Nutella GR', Decimal('1.0'), 'Mesa 11')
(13272, 4558, '# Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13273, 4558, '---- servir depois ----', Decimal('1.0'), 'Mesa 11')
(13274, 4558, 'Nutella Mor MD', Decimal('1.0'), 'Mesa 11')
(13275, 4558, '# Para Levar', Decimal('1.0'), 'Mesa 11')

输出表:

(13264, 4558, 'Funghi GR', '+ Champinhons | + Alface | - R\xc3\xbacola', Decimal('1.0'), 'Mesa 11')
(13268, 4558, 'Formaggi GR', 'Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13271, 4558, 'Nutella GR', '!SERVIR DEPOIS! | Cortar em dois', Decimal('1.0'), 'Mesa 11')
(13274, 4558, 'Nutella Mor MD', '!SERVIR DEPOIS! | Para Levar', Decimal('1.0'), 'Mesa 11')

Tags: posidiflineordertemplateproductdp
2条回答

你好像有两张桌子。这样你只需要访问数据库2次,而不是很多次。在

从表中获取数据

表一

ID     ORDER PRODUCT                    QTY     CAT
12811  4419  "Crudo GR"                 1.0       1
12812  4419  "Salame e Grana GR"        1.0       1
12813  4419  "   servir depois   "  1.0       7
12814  4419  "Nutella Ban GR"           1.0       3
12815  4419  "# Cortar em dois"         1.0       7

以表格形式获取数据

^{pr2}$

尝试将Intr放在最后一行:

newTable = [] 
Intr     = ''
LineCt   = 0


for line in fetch_lines:
    if line[2].startswith('#') or line[2].startswith('  '): 
        # Within this if statement you can make adjustment to text item
        if line[2].startswith('#'):
           Intr =  Intr + " Cortar em dois"
           LineCt +=1
        if line[2].startswith('  '):
           Intr =  '!SERVIR DEPOIS!' + Intr
           LineCt +=1   

for i,line in enumerate(fetch_lines):
    if line[2].startswith('#') or line[2].startswith('  '): pass        
    elif i == len(fetch_lines) - LineCt:
        newTable.append([line[0],line[1], line[2], Intr , "" ])
        Intr     = ''
    elif i < len(fetch_lines):
        newTable.append([line[0],line[1],line[2], '', "" ])        

print Intr        
for e in newTable: print e

输出:

  [12811, 4419, 'Crudo GR', '', '']
    [12812, 4419, 'Salame e Grana GR', '', '']
    [12814, 4419, 'Nutella Ban GR', '!SERVIR DEPOIS! Cortar em dois', ''

]

在@Merlin的大力帮助下,临时解决了这个问题,他把我带到了正确的方向,但我需要整理代码。最大的诀窍是从表中选择DESC中的行。在

po_lines = '''SELECT pos_order_line.id, pos_order_line.order_id, product_template.name, pos_order_line.qty, product_template.pos_categ_id
           FROM public.pos_order_line, public.product_template
           WHERE pos_order_line.product_id = product_template.id AND  pos_order_line.order_id = %s
           AND (product_template.pos_categ_id != 5 AND product_template.pos_categ_id != 6)
           ORDER BY pos_order_line.id DESC'''

cur.execute(po_lines,[order]); fetch_lines = cur.fetchall()
instr = ''; newTable = []

for i, line in enumerate(fetch_lines):
    if line[2].startswith('#') or line[2].startswith('  '):
        if line[2].startswith('#'):
            instr = instr + line[2][2:]
        if line[2].startswith('  '):
            line_in = fetch_lines[i-1]
            extract_line = tuple([item[3] for item in newTable if line_in[0] in item])
            newTable = [t for t in newTable if t[0] != line_in[0]]
            instr = '!SERVIR DEPOIS!/' + extract_line[0]
            newTable.append((line_in[0], line_in[1], line_in[2], instr))
            instr = ''
    else:
        newTable.append((line[0], line[1], line[2], instr))
        instr = ''

for i,l in enumerate(newTable[::-1]):
    print i,l

结果:

^{pr2}$

我确信我的代码可以更好,但在旧版本中,我需要80多行代码来归档。对于我的Python知识来说,这是一个巨大的进步。在

相关问题 更多 >

    热门问题