1)
def get_or_create(table, required_fields={}, updated_fields={}):
"""
Return record from table with passed field values. Create record if does not exist.
'table' is a DAL table reference, such as 'db.person'
'required_fields' is a dict, such as {'parent': 4, name: 'Richard'}
"""
if required_fields:
logic = reduce(lambda a, b : a & b, [table[k] == required_fields[k] for k in required_fields])
else:
logic = table.id > 0 # select any record if no fields passed
record = db(logic).select().first()
if record:
if updated_fields:
record.update_record(updated_fields)
return record
else:
updated_fields.update(required_fields)
return table.insert(**updated_fields)
2)
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 = db(logic).select().first()
if record is None:
record = table.insert(**required_fields)
record.update_record(**updated_fields)
Comments (0)