Defines the Model class. See Introduction to models.

(This module's source code is available here.)


pre_delete_handler(sender[, instance])

Before actually deleting an object, we override Django's behaviour concerning related objects via a GFK field.


Model(*args, **kwargs)

Lino's extension of the plain Django Model class.

class lino.core.model.Model(*args, **kwargs)

Bases: django.db.models.base.Model, lino.core.fields.TableRow

Lino's extension of the plain Django Model class.


This is defined by Django.

allow_cascaded_copy = frozenset({})

A set of names of ForeignKey or GenericForeignKey fields of this model that cause objects to be automatically duplicated when their master gets duplicated.

If this is a simple string, Lino expects it to be a space-separated list of filenames and convert it into a set at startup.

allow_cascaded_delete = frozenset({})

A set of names of ForeignKey or GenericForeignKey fields of this model that allow for cascaded delete.

Unlike with Dango's on_delete attribute you control cascaded delete behaviour on the model whose instances are going to be deleted.

If this is a simple string, Lino expects it to be a space-separated list of filenames and convert it into a set at startup.

Lino by default forbids to delete any object that is referenced by other objects. Users will get a message of type "Cannot delete X because n Ys refer to it".

Example: Lino should not refuse to delete a Mail just because it has some Recipient. When deleting a Mail, Lino should also delete its Recipients. That's why lino_xl.lib.outbox.models.Recipient has allow_cascaded_delete = 'mail'.

This is also used by lino.mixins.duplicable.Duplicate to decide whether slaves of a record being duplicated should be duplicated as well.

At startup (in kernel_startup) Lino automatically sets on_delete to PROTECT for all FK fields that are not listed in the allow_cascaded_delete of their model.


The SubmitInsert action to be executed when the when the users submits an insert window.

See lino.mixins.dupable for an example of how to override it.

allow_merge_action = False

Whether this model should have a merge action.

See lino.core.merge.MergeAction

Set this to False if you really don't want this model to occur in the site-wide search (lino.modlib.about.SiteSearch).

quick_search_fields = None

Explicitly specify the fields to be included in queries with a quick search value.

In your model declarations this should be either None or a string containing a space-separated list of field names. During server startup resolves it into a tuple of data elements.

If it is None, Lino installs a list of all CharFields on the model.

If you want to not inherit this field from a parent using standard MRO, then you must set that field explictly to None.

This is also used when a gridfilter has been set on a foreign key column which points to this model.

Special quick search strings

If the search string starts with "#", then Lino searches for a row with that primary key.

If the search string starts with "*", then Lino searches for a row with that reference.

quick_search_fields_digit = None

Same as quick_search_fields, but this list is used when the search text contains only digits (and does not start with '0').

active_fields = frozenset({})

If specified, this is the default value for active_fields of every Table on this model.

hidden_elements = frozenset({})

If specified, this is the default value for hidden_elements of every Table on this model.

preferred_foreignkey_width = None

The default preferred width (in characters) of widgets that display a ForeignKey to this model.

If not specified, the default default preferred_width for ForeignKey fields is 20.

workflow_state_field = None

If this is set on a Model, then it will be used as default value for workflow_state_field of all tables based on this Model.

workflow_owner_field = None

If this is set on a Model, then it will be used as default value for lino.core.table.Table.workflow_owner_field on all tables based on this Model.

change_watcher_spec = None

Internally used by watch_changes()

summary_row_template = None

An optional name of a template to use for as_summary_row().

classmethod collect_virtual_fields()

Declare every virtual field defined on this model to Django.

We use Django's undocumented add_field() method.

Make a copy if the field is inherited, in order to avoid side effects like #2592.

Raise an exception if the model defines both a database field and a virtual field of same name.


Return a set of names of fields that should be disabled (not editable) for this record.

See Disabling individual fields.


Double-check to avoid "murder bug" (20150623).

delete_veto_message(m, n)

Return the message Cannot delete X because N Ys refer to it.

classmethod define_action(**kw)

Adds one or several actions or other class attributes to this model.

Attributes must be specified using keyword arguments, the specified keys must not yet exist on the model.

Used e.g. in to add the UpdateReminders action to :class: lino.modlib.users.models.User.

Or in lino_xl.lib.invoicing.models for defining a custom chooser.

classmethod hide_elements(*names)

Mark the named data elements (fields) as hidden. They remain in the database but are not visible in the user interface.

classmethod add_param_filter(qs, lookup_prefix='', **kwargs)

Add filters to queryset using table parameter fields.

This is called for every simple parameter.

Usage examples: DeploymentsByTicket, lino_book.projects.min3.lib.contacts.

classmethod create_from_choice(text)

Called when a learning combo has been submitted. Create a persistent database object if the given text contains enough information.

classmethod choice_text_to_dict(text)

Return a dict of the fields to fill when the given text contains enough information for creating a new database object.

classmethod lookup_or_create(lookup_field, value, **known_values)

Look up whether there is a model instance having lookup_field with value value (and optionally other known_values matching exactly).

If it doesn't exist, create it and emit an auto_create signal.

classmethod quick_search_filter(search_text, prefix='')

Return the filter expression to apply when a quick search text is specified.


Override this to set default values that depend on the request.

The difference with Django's pre_init and post_init signals is that (1) you override the method instead of binding a signal and (2) you get the action request as argument.

Used e.g. by lino_xl.lib.notes.Note.

before_ui_save(ar, cw)

A hook for adding custom code to be executed each time an instance of this model gets updated via the user interface and before the changes are written to the database.

Consider using the pre_ui_save signal instead.

Example in to mark the event as user modified by setting a default state.

after_ui_save(ar, cw)

Like before_ui_save(), but after the changes are written to the database.


ar: the action request

cw: the ChangeWatcher

object, or None if this is a new instance.

Called after a PUT or POST on this row, and after the row has been saved.

Used by lino_welfare.modlib.debts.models.Budget to fill default entries to a new Budget, or by lino_welfare.modlib.cbss.models.CBSSRequest to execute the request, or by lino_welfare.modlib.pcsw.models.Coaching lino.modlib.vat.models.Vat. Or lino_welfare.modlib.households.models.Household overrides this in order to call its populate method.


Hook to define custom behaviour to run when a user has created a new instance of this model.


Save this instance and fire related behaviour.

get_row_permission(ar, state, ba)

Returns True or False whether this database object gives permission to the ActionRequest ar to run the specified action.


Called by lino.modlib.gfks.Controllable.


Called by lino.modlib.gfks.Controllable.


Return or yield a list of (type,partner) tuples to be used as recipents when creating an outbox.Mail from this object.


Return or yield a list of Partners to be used as recipents when creating a posting.Post from this object.

on_duplicate(ar, master)

Called after duplicating a row on the new row instance.

Also called recursively on all related objects. Where "related objects" means those which point to the master using a FK which is listed in allow_cascaded_delete.

Called by the lino.mixins.duplicable.Duplicate action.

ar is the action request that asked to duplicate.

If master is not None, then this is a cascaded duplicate initiated by a duplicate() on the specified master.

Note that this is called before saving the object for the first time.

Obsolete: On the master (i.e. when master is None), this is called after having saved the new object for a first time, and for related objects (master is not None) it is called before saving the object. But even when an overridden on_duplicate() method modifies a master, you don't need to save() because Lino checks for modifications and saves the master a second time when needed.

after_duplicate(ar, master)

Called by lino.mixins.duplicable.Duplicate on the new copied row instance, after the row and it's related fields have been saved.

ar is the action request that asked to duplicate.

ar.selected_rows[0] contains the original row that is being copied, which is the master parameter

before_state_change(ar, old, new)

Called by set_workflow_state() before a state change.

after_state_change(ar, old, new)

Called by set_workflow_state() after a state change.

set_workflow_state(ar, state_field, target_state)

Called by workflow actions (ChangeStateAction) to perform the actual state change.

after_send_mail(mail, ar, kw)

Called when an outbox email controlled by self has been sent (i.e. when the lino_xl.lib.outbox.models.SendMail action has successfully completed).


Return a raw HTML string representing this object in a data view as a single paragraph.

The string should represent a single <p>.

If summary_row_template is set, this will render this object using the named template, otherwise it will call summary_row() and wrap the result into a paragraph.

summary_row(ar, **kw)

Yield a sequence of ElementTree elements that represent this database object in a summary panel.

The elements will be wrapped into a <p> by as_summary_row().

The default representation is the text returned by __str__() in a link that opens the detail view on this database object.

The description may vary depending on the given action request.

For example a partner model of a given application may want to always show the city of a partner unless city is among the known values:

def summary_row(self, ar):
    elems = [ar.obj2html(self)]
    if and not ar.is_obvious_field("city"):
        elems += [" (", ar.obj2html(, ")"]
    return elems

Note that this is called by the class method of same name on lino.core.actors.Actor, which may be customized and may decide to not call the model method.

TODO: rename this to row2summary and write documentation.


Used when implementing Polymorphism.

classmethod set_widget_options(name, **options)

Set default values for the widget options of a given element.

Usage example:

JobSupplyment.set_widget_options('duration', width=10)

has the same effect as specifying duration:10 each time when using this element in a layout.

List of widget options that can be set:

width preferred_width label editable preferred_height hide_sum

classmethod get_request_queryset(ar, **filter)

Return the base queryset for tables on this object.

The optional filter keyword arguments, if present, are applied as additional filter. This is used only in UNION tables on abstract model mixins where filtering cannot be done after the join.

classmethod get_user_queryset(user, **filter)

Get the base queryset, used for user level row filtering in

classmethod resolve_states(states)

Convert the given string states into a set of state objects.

The states specifier must be either a set containing state objects or a string containing a space-separated list of valid state names. If it is a string, convert it to the set.

classmethod get_actions_hotkeys()

Return or yield a list of hotkeys to be linked to named actions.

[{'key': key, 'ctrl': Bool, 'shift': Bool, 'ba': action_name}]

classmethod get_layout_aliases()

Yield a series of (ALIAS, repl) tuples that cause a name ALIAS in a layout based on this model to be replaced by its replacement repl.

classmethod add_picker(fldname)

Add a picker for the named choicelist field.

A picker is a virtual field that shows all the available choices in a way that you can click on them to change the underlying choicelist field's value. Functionally similar to a radio button, but causes immediate submit instead of waiting until the form gets submitted.

classmethod django2lino(model)

Injects additional methods into a pure Django model that does not inherit from lino.core.model.Model. Used by lino.core.kernel

classmethod get_subclasses_graph()

Returns an internationalized graphviz directive representing the polymorphic forms of this model.

Usage example:

.. django2rst::

    with dd.translation.override('de'):
lino.core.model.pre_delete_handler(sender, instance=None, **kw)

Before actually deleting an object, we override Django's behaviour concerning related objects via a GFK field.

In Lino you can configure the cascading behaviour using allow_cascaded_delete.

See also GenericForeignKey fields.

It seems that Django deletes generic related objects only if the object being deleted has a GenericRelation field (according to Why won't my GenericForeignKey cascade when deleting?). OTOH this statement seems to be wrong: it happens also in my projects which do not use any GenericRelation. As test_broken_gfk shows.

TODO: instead of calling disable_delete here again (it has been called earlier by the delete action before asking for user confirmation), Lino might change the on_delete attribute of all ForeignKey fields which are not in allow_cascaded_delete from CASCADE to PROTECTED at startup.