I guess these don't exist so I've created my own versions, pasted
below. Would it be worth including something like this in the DAL?
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 = None
for field, value in fields.items():
e = table[field] == value
logic = e if logic is None else logic & e
record = 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 = None
for field, value in required_fields.items():
e = table[field] == value
logic = e if logic is None else logic & e
record = db(logic).select().first()
if record is None:
record = table.insert(**required_fields)
record.update_record(**updated_fields)
On Jan 28, 11:24 pm, Richard <[email protected]> wrote:
> I want to get the ID of a record with certain fields, and create it if
> not already existing. Is there a shortcut for this common operation?
> In Django it is called "get_or_create()"
>
> Also, is there a shortcut for update_or_create()?
>
> Thanks,
> Richard
--
You received this message because you are subscribed to the Google Groups
"web2py-users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/web2py?hl=en.