How to get specific record in json controller in Odoo 12

久未见 提交于 2021-02-11 12:56:59

问题


My question says it all. I already did a controller to search all records from specific model.

Now I want to search just one record (by its id) from the same model.

My controller for all records is this:

@http.route('/get_sales', type='json', auth='user')
    def get_sales(self):
        sales_rec = request.env['sale.order'].search([])
        sales = []
        for rec in sales_rec:
            vals = {
                'id': rec.id,
                'name': rec.name,
                'partner_id': rec.partner_id,
            }
            sales.append(vals)
        data = {'status': 200, 'response': sales, 'message': 'All sales returned'}
        return data

So, what I have to add to get just one record depending on its ID.

Thanks.


回答1:


Firstly, change your controller route like so:

@http.route(['/get_sales', '/get_sales/<int:order_id>'], type='json', auth='user')

By doing that you now have the option to call your route with or without an order_id.

Secondly, change your method like so:

def get_sales(self, order_id=None):

Now you can add some logic into your method:

if order_id:
    domain = [('id', '=', order_id)]
else:
    domain = []
sales_rec = request.env['sale.order'].search(domain)



回答2:


sale_rec = request.env['sale.order'].search([('id','=',YOURID)])

or

sale_rec = request.env['sale.order'].browse(YOURID)

Both return the selected object



来源:https://stackoverflow.com/questions/63624527/how-to-get-specific-record-in-json-controller-in-odoo-12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!