I have been using these related functions:
def get_or_create(table, fields): """ Return ID of record from table with passed field values. Create record if does not exist. 'table' is a DAL table reference, such as 'db.person' 'fields' is a dict, such as {'parent': 4, name: 'Richard'} """ logic = reduce(lambda a, b : a & b, [table[k] == fields[k] for k in fields]) record = self.db(logic).select(table['id']).first() if record: return record.id else: return table.insert(**fields).id def update_or_create(table, required_fields, updated_fields): """ Modify record from table that matches 'required_fields' with 'updated_fields'. If record with 'required_fields' does not exist then create it. 'table' is a DAL table reference, such as 'db.person' 'required_fields' and 'updated_fields' are dicts, such as {'parent': 4, name: 'Richard'} """ logic = reduce(lambda a, b : a & b, [table[k] == required_fields[k] for k in required_fields]) record = self.db(logic).select().first() if record is None: record = table.insert(**required_fields) record.update_record(**updated_fields) On Mar 17, 7:45 am, Michael Toomim <too...@gmail.com> wrote: > Hi guys, I've found the following functions to be commonly useful in > practice. Has anyone else written anything similar? Is there a better > idiom here, or better names or interfaces for these? > > def get_one(query): > result = db(query).select() > assert len(result) <= 1, "GAH get_one called when there's MORE > than one!" > return result[0] if len(result) == 1 else None > > def get_or_make_one(query, table, default_values): > result = get_one(query) > if not result: > table.insert(**default_values) > return get_one(query) -- You received this message because you are subscribed to the Google Groups "web2py-users" group. To post to this group, send email to web...@googlegroups.com. To unsubscribe from this group, send email to web2py+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/web2py?hl=en.