我正在使用web2py框架开发一个db项目,在该项目中,我需要编写一个查询,以查找通过乘以数量和单位价格获得的总账单金额。
表格:
db.define_table('item',
Field('name', notnull = True,unique=True),
Field('price'),
format = '%(name)s')
db.define_table('customer',
Field('item_name', 'reference item'),
Field('item_price','reference item' ),
Field('name', notnull = True),
Field('email',requires = IS_EMAIL(error_message='invalid email!'),unique='True'),
Field('adress',requires=IS_NOT_EMPTY()),
Field('city'),
Field('quantity'),
Field('state',default='KARNATAKA'),
Field('contact_number'),
Field('Total_price',
compute=lambda r: r['quantity'] * r['item_price']),
format='%(name)s')
db.item.name.requires = IS_NOT_IN_DB(db, db.item.name)
db.customer.item_name.requires = IS_IN_DB(db, db.item.id, '%(name)s')
db.item.price.requires = IS_NOT_IN_DB(db, db.item.price)
db.customer.item_price.requires = IS_IN_DB(db, db.item.id, '%(price)s')`
输出:
customer.id customer.item_name customer.item_price customer.name customer.email customer.adress customer.city customer.quantity
customer.state customer.contact_number customer.Total_price:
Gold Winner Palm Reshma reshmagunda@g... Near Bus stand Mudalgi 2 KARNATAKA 7423089630 2222
如果我将此查询用于单表计算,它可以正常工作,但对于外键链接表,我会得到垃圾值。。。
价格字段在项目中;对于上面的查询,它是65/-
,它是客户表的外键,数量是2
。预期输出为130
,但生成的查询输出为2222
。
我需要做哪些修改才能获得预期的输出?
引用字段只存储引用记录的记录ID,而不存储引用记录中的实际字段值。因此,以下字段:
Field('item_price', 'reference item')
不存储项目表中的价格值——它只是存储项目表的特定项目的记录ID。要获得商品价格本身,您需要查询商品表(这可以通过联接或单独的查询来完成)。
这意味着item_name和item_price字段是多余的——您只需要一个引用item表的字段,所以用以下内容替换这两个字段:
Field('item', 'reference item')
然后可以将计算字段更改为:
Field('Total_price', compute=lambda r: r.quantity * db.item(r.item).price)
r.item
是关联项目的记录ID,所以db.item(r.item)
获取该记录,因此db.item(r.item).price
是该记录中价格字段的值。
此外,请注意,默认字段类型为"字符串",这是价格字段的类型,前提是您没有明确指定类型。您可能希望将它们指定为十进制字段。