如何在openerp(或其他相同的字段)中检索具有相同名称值的记录?
The solution of using a manual SQL query to group by name
as suggested by Ruchir is probably the simplest, but a bit low-level. You can also do it using the read_group()
API method that performs a similar GROUP BY
query, but without bypassing access control mechanisms and model business logic.
The read_group
method takes a search domain (similarly to search()
), a list of fields to read (similarly to read()
) and a list of fields to group by. This method is documented in the OpenERP API . It returns an ordered list of dictionaries with the grouped data and some extra values, including the number of record in each group, stored in a key named <grouped_field>_count
, which you could use to find duplicates.
For example if you look for duplicate name
values, without any other search criterion:
def duplicate_names(self, cr, uid, context=None):
# Note: context not propagated for brevity of example
groups = self.read_group(cr, uid, [], ['name'], ['name'])
duplicate_names = [g['name'] for g in groups if g['name_count'] > 1]
print "Duplicates names:", duplicate_names
if duplicate_names:
# It's easy to find out the IDs of duplicate records for each name,
# here is for the first one
duplicate_ids = self.search(cr, uid, [('name', '=', duplicate_names[0])])
print "Duplicate IDs for %r: %s" % (duplicate_names[0], duplicate_ids)
You can find duplicate records with a direct SQL query in the database. As an example, this is how you can find duplicate names in the Contact Addresses:
cr.execute("""
SELECT name, id, partner_id FROM res_partner_address
WHERE name in (SELECT name
FROM res_partner_address
GROUP BY name
HAVING (COUNT(name) > 1))""")
print cr.dictfetchall()
Instead of cr.dictfetchall()
you can use cr.fetchall()
to get the results as a list of tuples rather than dicts.
If you have a specific value for a field 'name' to be searched, then the domain to be searched is
domain = [('name', '=', your_value)]
If you have a list of values to be searched then
domain = [('name', 'in', list_of_values)]
If you want to search a field 'name' with similar value then
domain = [('name','ilike',your_value)]
Now you can search
our_pool = self.pool.get('your.obj.name')
ids = our_pool.search(cr, uid, domain, context=context)
Now you can browse the ids we get
our_objs = our_pool.browse(cr, uid, ids, context)
You should first read the document first: http://doc.openerp.com/v6.0/developer/2_5_Objects_Fields_Methods/methods.html
For this question you will need first a 'search' then a 'browse' (or 'read') for example:
obj = self.pool.get('your.obj.name')
ids = obj.search(cr, uid, [('name','=',your_value)], context=context)
records = obj.browse(cr, uid, ids, context=context)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.