示例1:

# -*- encoding: utf-8 -*-
import pooler
import logging
import
netsvc
import tools
logger = netsvc.Logger()
import datetime
import
time
import math
from osv import fields,osv
from
openerp.tools.translate import _  #用于翻译代码中的静态字符串

class res_users(osv.osv):
    _name =
"res.users"
    _inherit = 'res.users'
   

    _columns={
       
'location_ids': fields.many2many('stock.location', id1='user_id',
id2='location_id', string=u'允许的库位'),     

    }
   
res_users()

class stock_picking(osv.osv):
    _name =
"stock.picking"
    _inherit = 'stock.picking'

    def _get_location_ids(self, cr, uid, ids, name,
arg, context=None):
        res =
{}
        for pick in self.browse(cr,
uid, ids):
           
location_ids =
set()
            for
move in
pick.move_lines:
               
location_ids.add(move.location_id.id)
           
res[pick.id] = list(location_ids)
       
return res

    def _location_ids_search(self, cr, uid, obj, name,
args, context=None):
        for
arg in
args:
            if
arg[0] ==
'location_ids':
               
operator =
arg[1]
               
search_term = arg[2]
        if operator
and
search_term:
           
move_obj =
self.pool.get('stock.move')
           
move_ids = move_obj.search(cr,
uid,
               
[('location_id', operator, search_term)],
context=context)
       
else:
           
move_ids = []
        return
[('move_lines', 'in', move_ids)]
   

    def _get_location_dest_ids(self, cr, uid, ids,
name, arg, context=None):
       
res = {}
        for pick in
self.browse(cr, uid,
ids):
           
location_ids =
set()
            for
move in
pick.move_lines:
               
location_ids.add(move.location_id.id)
           
res[pick.id] = list(location_ids)
       
return res

    def _location_dest_ids_search(self, cr, uid, obj,
name, args,
context=None):
        for arg in
args:
            if
arg[0] ==
'location_dest_ids':
               
operator =
arg[1]
               
search_term = arg[2]
        if operator
and
search_term:
           
move_obj =
self.pool.get('stock.move')
           
move_ids = move_obj.search(cr,
uid,
               
[('location_dest_id', operator, search_term)],
context=context)
       
else:
           
move_ids = []
        return
[('move_lines', 'in', move_ids)]

_columns = { 

       
'location_ids':fields.function(_get_location_ids,
fnct_search=_location_ids_search,
           
method=True, type='many2many', relation='stock.location', string='源库位
ids'),
               

       
'location_dest_ids':fields.function(_get_location_dest_ids,
fnct_search=_location_dest_ids_search,
           
method=True, type='many2many', relation='stock.location', string='目标库位
ids'),
    }

stock_picking()

示例2:

class stock_production_lot(osv.osv):

_name = 'stock.production.lot'

_description = 'Serial Number'

    def _get_stock(self, cr, uid, ids, field_name, arg, context=None):

""" Gets stock of products for locations

@return: Dictionary of values

"""

if context is None:

context = {}

if 'location_id' not in context:

locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')], context=context)

else:

locations = context['location_id'] and [context['location_id']] or []

if isinstance(ids, (int, long)):

ids = [ids]

res = {}.fromkeys(ids, 0.0)

if locations:

cr.execute('''select

prodlot_id,

sum(qty)

from

stock_report_prodlots

where

location_id IN %s and prodlot_id IN %s group by prodlot_id''',(tuple(locations),tuple(ids),))

res.update(dict(cr.fetchall()))

return res

    def _stock_search(self, cr, uid, obj, name, args, context=None):

""" Searches Ids of products

@return: Ids of locations

"""

locations = self.pool.get('stock.location').search(cr, uid, [('usage', '=', 'internal')])

cr.execute('''select

prodlot_id,

sum(qty)

from

stock_report_prodlots

where

location_id IN %s group by prodlot_id

having  sum(qty) '''+ str(args[0][1]) + str(args[0][2]),(tuple(locations),))

res = cr.fetchall()

ids = [('id', 'in', map(lambda x: x[0], res))]

return ids

_columns = {

'name': fields.char('Serial Number', size=64, required=True, help="Unique Serial Number, will be displayed as: PREFIX/SERIAL [INT_REF]"),

'ref': fields.char('Internal Reference', size=256, help="Internal reference number in case it differs from the manufacturer's serial number"),

'prefix': fields.char('Prefix', size=64, help="Optional prefix to prepend when displaying this serial number: PREFIX/SERIAL [INT_REF]"),

'product_id': fields.many2one('product.product', 'Product', required=True, domain=[('type', '<>', 'service')]),

'date': fields.datetime('Creation Date', required=True),

        'stock_available': fields.function(_get_stock, fnct_search=_stock_search, type="float", string="Available", select=True,

help="Current quantity of products with this Serial Number available in company warehouses",

digits_compute=dp.get_precision('Product Unit of Measure')),

'revisions': fields.one2many('stock.production.lot.revision', 'lot_id', 'Revisions'),

'company_id': fields.many2one('res.company', 'Company', select=True),

'move_ids': fields.one2many('stock.move', 'prodlot_id', 'Moves for this serial number', readonly=True),

}

_defaults = {

'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),

'name': lambda x, y, z, c: x.pool.get('ir.sequence').get(y, z, 'stock.lot.serial'),

'product_id': lambda x, y, z, c: c.get('product_id', False),

}

_sql_constraints = [

('name_ref_uniq', 'unique (name, ref)', 'The combination of Serial Number and internal reference must be unique !'),

]

stock_production_lot()

示例3:

# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
import
decimal_precision as dp
from openerp.addons.stock.product import
product_product as spp
from openerp.addons.product.product import
product_product as pp

_product_available = spp._product_available
_product_lst_price =
pp._product_lst_price

SORTABLE_FUNC_FIELD = ('qty_available', 'virtual_available', 'lst_price')

def condition(operand, left, right):
   
if operand == '=':
        operand =
'=='
    return eval('
'.join((str(left),operand,str(right))))

class product_product(osv.osv):
   
_inherit = "product.product"

    def _search_fnct(self, cr, uid, args, qty_type,
context=None):
        context =
context or {}
        print 'context',
context
        ids = self.search(cr, uid,
[], context=context)
        qty_products
= self.read(cr, uid, ids, [qty_type],
context=context)
        res =
[]
        for q in
qty_products:
           
if condition(args[0][1], q[qty_type], args[0][2]):

               
res.append(q['id'])
        return [('id',
'in', res)]
   
    def
_search_qty_available(self, cr, uid, obj, name, args,
context):
        return
self._search_fnct(cr, uid, args, 'qty_available', context)

    def _search_virtual_available(self, cr, uid, obj,
name, args, context):
       
return self._search_fnct(cr, uid, args, 'virtual_available', context)

    def _search_lst_price(self, cr, uid, obj, name,
args, context):
        return
self._search_fnct(cr, uid, args, 'lst_price',
context)
           

    _columns =
{
        'qty_available':
fields.function(_product_available,
           
multi='qty_available',
type='float',
           
digits_compute=dp.get_precision('Product Unit of
Measure'),
           
fnct_search=_search_qty_available,
           
string='Quantity On
Hand',
           
help="Current quantity of
products.\n"
                
"In a context with a single Stock Location, this includes
"
                
"goods stored at this Location, or any of its
children.\n"
                
"In a context with a single Warehouse, this includes
"
                
"goods stored in the Stock Location of this Warehouse, or
any"
                
"of its
children.\n"
                
"In a context with a single Shop, this includes goods
"
                
"stored in the Stock Location of the Warehouse of this Shop,
"
                
"or any of its
children.\n"
                
"Otherwise, this includes goods stored in any Stock Location
"
                
"with 'internal' type."),
       
'virtual_available':
fields.function(_product_available,
           
multi='qty_available',
type='float',
           
digits_compute=dp.get_precision('Product Unit of
Measure'),
           
fnct_search=_search_virtual_available,
           
string='Forecasted
Quantity',
           
help="Forecast quantity (computed as Quantity On Hand
"
                
"- Outgoing +
Incoming)\n"
                
"In a context with a single Stock Location, this includes
"
                
"goods stored in this location, or any of its
children.\n"
                
"In a context with a single Warehouse, this includes
"
                
"goods stored in the Stock Location of this Warehouse, or
any"
                
"of its
children.\n"
                
"In a context with a single Shop, this includes goods
"
                
"stored in the Stock Location of the Warehouse of this Shop,
"
                
"or any of its
children.\n"
                
"Otherwise, this includes goods stored in any Stock Location
"
                
"with 'internal' type."),
       
'lst_price' : fields.function(_product_lst_price,
type='float',
           
string='Public Price',
fnct_search=_search_lst_price,
           
digits_compute=dp.get_precision('Product
Price')),
        }

def search(self, cr, uid, args, offset=0, limit=None,
order=None,
           
context=None, count=False):
       
context = context or {}
        func_flds
= []
        if
order:
           
order_part =
order.split(',')[0]
           
order_split = order_part.strip().split('
')
           
order_field =
order_split[0].strip()
           
order_direction = order_split[1].strip() if len(order_split) == 2 else
''
            if
order_field in
SORTABLE_FUNC_FIELD:
                   
func_flds.append((order_field,
order_direction))
        ids =
super(product_product, self).search(cr, uid, args, offset,
limit,
               
order, context, count)
        if
func_flds:
           
for fld, order in
func_flds:
               
val = self.read(cr, uid, ids, [fld],
context=context)
               
sorted_val = sorted(val, key=lambda x:
x[fld],
                       
reverse=(order=='DESC'))
           
ids = map(lambda x: x['id'],
sorted_val)
        return ids

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

openerp学习笔记 计算字段支持搜索的更多相关文章

  1. openerp学习笔记 计算字段、关联字段(7.0中非计算字段、关联字段只读时无法修改保存的问题暂未解决)

    计算字段.关联字段,对象修改时自动变更保存(当 store=True 时),当 store=False 时,默认不支持过滤和分组7.0中非计算字段.关联字段只读时无法修改保存的问题暂未解决 示例代码: ...

  2. iView学习笔记(三):表格搜索,过滤及隐藏列操作

    iView学习笔记(三):表格搜索,过滤及隐藏某列操作 1.后端准备工作 环境说明 python版本:3.6.6 Django版本:1.11.8 数据库:MariaDB 5.5.60 新建Django ...

  3. springmvc学习笔记(19)-RESTful支持

    springmvc学习笔记(19)-RESTful支持 标签: springmvc springmvc学习笔记19-RESTful支持 概念 REST的样例 controller REST方法的前端控 ...

  4. openerp学习笔记 搜索视图(自己创建的、自己的、本部门的、本部门及下属部门的、今日的、日期从,日期至、多条件模糊搜索、or、and)

    自己创建的: domain="[('create_uid','=',uid)]" 自己的: domain="[('employee_id','=','#kl_user_e ...

  5. go 学习笔记之是否支持以及如何实现继承

    熟悉面向对象的小伙伴们可能会知道封装,继承和多态是最主要的特性,为什么前辈们会如此看重这三种特性,真的那么重要吗? 什么是封装 什么是封装,封装有什么好处以及怎么实现封装? 相信大多数小伙伴们都有自己 ...

  6. ES[7.6.x]学习笔记(九)搜索

    搜索是ES最最核心的内容,没有之一.前面章节的内容,索引.动态映射.分词器等都是铺垫,最重要的就是最后点击搜索这一下.下面我们就看看点击搜索这一下的背后,都做了哪些事情. 分数(score) ES的搜 ...

  7. SQL学习之计算字段的用法与解析

    一.计算字段 1.存储在数据库表中的数据一般不是应用程序所需要的格式.大多数情况下,数据表中的数据都需要进行二次处理.下面举几个例子. (1).我们需要一个字段同时显示公司名和公司地址,但这两个信息存 ...

  8. openerp学习笔记 视图样式(表格行颜色、按钮,字段只读、隐藏,按钮状态、类型、图标、权限,group边距,聚合[合计、平均],样式)

    表格行颜色:             <tree string="请假单列表" colors="red:state == 'refuse';blue:state = ...

  9. openerp学习笔记 domain 增加扩展支持,例如支持 <field name="domain">[('type','=','get_user_ht_type()')]</field>

    示例代码1,ir_action_window.read : # -*- coding: utf-8 -*-from openerp.osv import fields,osv class res_us ...

随机推荐

  1. batchExportPNG.py不是我的代码

    #coding=gbk#@author lifc,20140806#批量制作输出专题图import arcpy,os,time,math #testpath=raw_input("testp ...

  2. Handsontable 学习笔记-Methods

    Handson: 亲自实践 先给出数据源和基本配置: var data =[ ["A1","B1","C1","D1"] ...

  3. Uva 10596 - Morning Walk 欧拉回路基础水题 并查集实现

    题目给出图,要求判断不能一遍走完所有边,也就是无向图,题目分类是分欧拉回路,但其实只要判断度数就行了. 一开始以为只要判断度数就可以了,交了一发WA了.听别人说要先判断是否是联通图,于是用并查集并一起 ...

  4. [Android 开源项目学习]Android的UITableView(1)

         最近由于项目加急,手里有好多看了差不多的开源项目,其中好多是大家经常用到的.图片的缓存BitmapFun(Android的文档中),AfinalMap,下拉刷新PullToRefresh等等 ...

  5. Umbraco(3) - CSS & Javascript(翻译文档)

    原文地址:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/umbraco3css-javascript/ CSS & Jav ...

  6. 最初步的正则表达式引擎:生成nfa

    这个版本修改了前面版本的两个个bug. 第一个:识别到字符集的时候,只是将name_number加1,却并不对reg_pattern_table[name_number]进行初始化. 第二个:识别到假 ...

  7. Http error code

    概要 当用户试图通过HTTP或文件传输协议(FTP)访问一台正在运行Internet信息服务(IIS)的服务器上的内容时,IIS返回一个表示该请求的状态的数字代码.该状态代码记录在IIS日志中,同时也 ...

  8. 转: Android基于HLS和RTMP协议的第三方SDK选择

    转自: http://isunxu.xyz/android/between-rtmp-and-hls-third-party-choice/ 协议的详解网上资料都太多了,我就不赘述了.Android上 ...

  9. CSS+DIV布局应用(2015年06月10日)

    Div+css布局应用 一.html元素分类 2.1.顶级元素(Top-level element) 定义 组成html页面最顶级标签 特点 1. 不可设置宽高: 2. 必须在文档流中处于最高级位置: ...

  10. 【ASP.NET基础】客户端、服务器端的数据验证 + CKEditer

    1, 客户端 用Javascript进行验证,直接提示用户输入的数据是否符合规范,是否合法. 这样体验行比较好,客户端立即就可以得到反馈,而且减少了服务器端的数据交互. 这样前端数据验证并不是很安全, ...