martenframework / marten

The pragmatic web framework.
https://martenframework.com
MIT License
424 stars 24 forks source link

Add support for get or create query set helper #55

Closed ellmetha closed 1 year ago

ellmetha commented 1 year ago

Description

Models and query sets should provide a #get_or_create method allowing to do a record lookup based on one or more field predicates and, if the lookup returns zero results, create the corresponding record.

For example:

Tag.get_or_create(label: "crystal")

It should be noted that this method should allow to specify "default' field values when creating the new record if it is not found.

For example:

Tag.get_or_create(label: "crystal", defaults: { is_active: true })

An alternative #get_or_create! method should also be provided, but contrary to #get_or_create, this one should raise when creating the new record if it is invalid.