lino.core.choicelists

Defines the classes Choice and ChoiceList. See Introduction to choicelists.

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

Classes

CallableChoice(ChoiceList, name)

CallableChoiceSerializer(value)

Choice([value, text, names])

A constant value whose unicode representation depends on the current language at runtime.

ChoiceList(*args, **kw)

User-defined choice lists must inherit from this base class.

ChoiceListField([choicelist, verbose_name, ...])

A field that stores a value to be selected from a ChoiceList.

ChoiceListMeta

ChoiceListSerializer(value)

ChoiceSerializer(value)

MultiChoiceListField(choicelist[, ...])

A field whose value is a list of Choice instances.

UnresolvedValue(choicelist, value)

class lino.core.choicelists.Choice(value=None, text=None, names=None, **kwargs)

Bases: lino.core.fields.TableRow

A constant value whose unicode representation depends on the current language at runtime. Every item of a ChoiceList must be an instance of Choice or a subclass thereof.

value = None

(a string) The value to use e.g. when this choice is being stored in a database.

names = ''

A list of names to be used as attribute name on the choicelist for referring to this choice from application code.

If this is None or not specified, the choice is a nameless choice, which is a full-fledged choice object but is not accessible as a class attribute on its choicelist.

text = None

A translatable string containing the text to show to the user.

remove()

Remove this choice from its list.

Usage example see

get_typed_instance(model)

Used when implementing Polymorphism.

class lino.core.choicelists.ChoiceList(*args, **kw)

Bases: lino.core.tables.AbstractTable

User-defined choice lists must inherit from this base class.

max_length

The default max_length for fields using this choicelist.

item_class

The class of items of this list.

alias of Choice

default_value = None

A string with the name of a choice to be used as default value for fields using this list.

Note that this specifies the default default value for all ChoiceListField of this choicelist, including parameter fields.

You can remove that "default default value" for all tables by specifying default=''. There are two places where you can specify this: (a) on the parameter field itself (which then applies to all subtables) or (b) just on one table. For example (excerpt from lino_avanti.lib.avanti):

from lino_xl.lib.clients.choicelists import ClientStates
ClientStates.default_value = 'coached'

parameters = ObservedDateRange(
    ...
    client_state=ClientStates.field(blank=True, default=''))

Note that the default values of parameter fields of a table which is used as the models default table will apply for the choices of pointers to that model. Concrete use case is the choicelist of cal.Guest.partner in Lino Avanti which should show only coached clients. So instead of above code we actually now do:

class MyClients(My, Clients):
    @classmethod
    def param_defaults(self, ar, **kw):
        kw = super(MyClients, self).param_defaults(ar, **kw)
        kw.update(client_state='')
        return kw

The disadvantage is that when somebody does not want your default value, then they must explicitly specify default='' when defining a field on your choicelist.

preferred_foreignkey_width = 20

Default preferred with for ChoiceList fields to this list.

stored_name = None

Every subclass of ChoiceList will be automatically registered. Define this if your class's name clashes with the name of an existing ChoiceList.

show_values = False

Set this to True if the user interface should include the value attribute of each choice.

preferred_width = None

Preferred width (in characters) used by fields that refer to this list.

If this is None, then Lino calculates the value at startup, taking the length of the longest choice text. The hard-coded absolute minimum in that case is 4. Note that it calculates the value using the default site language and thus might guess wrong if the user language is not the default site language.

Note that by this we mean the width of the bare text field, excluding any UI-specific control like the trigger button of a combobox. That's why e.g. lino.modlib.extjs.ext_elems adds another value for the trigger button.

old2new = {}

A dict which maps old values to their new values.

This dict is consulted when an unknown value is read from database (e.g. during a migration). If if contains a replacement for the old value, Lino will return the choice with the new value.

classmethod get_data_rows(ar=None)
classmethod get_actor_label()

Compute the label of this actor. Called only if label is not set, and only once during site startup.

classmethod clear()

Clear the list, i.e. remove all items.

This is used when you want to restart from scratch for building a choicelist.

classmethod remove_item(i)

Remove the specified item from this list. Called by Choice.remove().

classmethod sort()

Sort the items by their value.

Used for example by lino_xl.lib.orders where we add a journal group to lino_xl.lib.ledger.JournalGroups and want it to come before the other groups.

classmethod field(*args, **kw)

Create and return a database field that points to one value of this choicelist.

The returned field is an instance of ChoiceListField. Returns a DummyField if the plugin which defines this choicelist is not installed.

classmethod multifield(*args, **kw)

Not yet implemented. Create a database field (a ChoiceListField) that holds a set of multiple values of this choicelist.

classmethod add_item_lazy(*args, **kwargs)

Run add_item() with these arguments when all plugins have been loaded.

This is used e.g. when declaring lino_xl.lib.ledger.VoucherTypes : a voucher type is defined using its ByJournal table, but the model of that table is not necessarily resolvable at that moment.

classmethod add_item(*args, **kwargs)

Instantiates a new choice and adds it to this list. Signature is that of the Choice.__init__() method (which might have been overridden if you defined a customized item_class.

classmethod get_pk_field()

See lino.core.actors.Actor.get_pk_field().

classmethod display_text(bc)

Return the text to be used for representing the given choice instance bc to the user.

Override this to customize the display text of choices. lino.modlib.users.UserGroups and lino.modlib.cv.models.CefLevel used to do this before we had the ChoiceList.show_values option.

This must be lazyly translatable because the result are also used to build the choices attribute of ChoiceListFields on this choicelist.

Note that Django's lazy function has a list of "resultclasses" which are used "so that the automatic forcing of the lazy evaluation code is triggered".

classmethod get_by_name(name, *args)

Supports the case that name is None (returns None then).

classmethod get_by_value(value, *args)

Return the item (a Choice instance) corresponding to the specified value.

classmethod as_callable(name)

Use this when you want to specify some named default choice of this list as a default value without removing the possibility to clear and re-populate the list after the field definition.

Usage example:

foo_state = MyStates.as_callable('foo')

This is used internally when you specify a string as default value of a choicelist field.

classmethod get_default_value()

Return the default default value for fields using this choicelist.

classmethod find(**fkw)

Find and return the choice which satisfies the given search criteria. Return None if no choice is found or if more than one choice is found.

classmethod get_text_for_value(value)

Return the text corresponding to the specified value.

class lino.core.choicelists.ChoiceListField(choicelist=None, verbose_name=None, force_selection=True, default=None, **kw)

Bases: django.db.models.fields.CharField

A field that stores a value to be selected from a ChoiceList.

ChoiceListField cannot be nullable since they are implemented as CharFields. Therefore when filtering on empty values in a database query you cannot use __isnull. The following query won't work as expected:

for u in users.User.objects.filter(user_type__isnull=False):

You must either check for an empty string:

for u in users.User.objects.exclude(user_type='')

or use the __gte operator:

for u in users.User.objects.filter(user_type__gte=dd.UserLevels.guest):
deconstruct()

Needed for Django 1.7+, see https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#custom-field-deconstruct-method

to_python(value)

See Django's docs about to_python().

property choices

HACK: Django by default stores a copy of our list when the choices of a field are evaluated for the first time. We don't want that because ChoiceLists may change afterwards.

get_prep_value(value)

Excerpt from Django docs: "If you override to_python() you also have to override get_prep_value() to convert Python objects back to query values."

class lino.core.choicelists.MultiChoiceListField(choicelist, verbose_name=None, max_values=10, **kw)

Bases: lino.core.choicelists.ChoiceListField

A field whose value is a list of Choice instances. Stored in the database as a CharField using a delimiter character.

get_prep_value(value)

This must convert the given Python value (always a list) into the value to be stored to database.