首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查询web2py表中的价格、外键字段、数量字段相乘得到的总账单金额

查询web2py表中的价格、外键字段、数量字段相乘得到的总账单金额
EN

Stack Overflow用户
提问于 2016-04-20 00:51:49
回答 1查看 87关注 0票数 0

我正在开发一个使用web2py框架的数据库项目,在这个项目中,我需要编写一个查询来查找通过将数量和unit_price相乘而获得的总账单金额。

表:

代码语言:javascript
复制
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')`

输出:

代码语言:javascript
复制
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

如果我使用这个查询进行单表计算,它工作得很好,但对于外键链接表,我得到的是垃圾值……

价格字段在item中,以上查询为65/-,customer表为外键,quantity为2。预期输出为130,但生成的查询输出为2222

我需要做哪些修改才能得到预期的输出?

EN

回答 1

Stack Overflow用户

发布于 2016-04-20 01:40:51

引用字段只存储被引用记录的记录ID --它们不存储被引用记录中的实际字段值。因此,下面的字段:

代码语言:javascript
复制
Field('item_price', 'reference item')

不存储item表中的价格值--它只是存储item表中特定项目的记录ID。要获得商品价格本身,您需要查询商品表(这可以通过连接或单独查询来完成)。

这意味着item_name和item_price字段是多余的--您只需要一个引用item表的字段,因此将这两个字段替换为如下所示:

代码语言:javascript
复制
Field('item', 'reference item')

然后,可以将计算字段更改为:

代码语言:javascript
复制
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是该记录中价格字段的值。

另外,请注意,默认的字段类型是"string",这是假定您没有显式指定类型的价格字段的类型。相反,您可能希望将它们指定为十进制字段。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36724700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档