问题
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