Welcome | Get started | Dive into Lino | Contribute | Topics | Reference | More

lookup_or_create and the auto_create signal

This document describes and tests the lookup_or_create method and the auto_create signal.

This page is a tested document and the following instructions are used for initialization:

>>> from lino import startup
>>> startup('lino_book.projects.auto_create.settings')
>>> from lino.api.doctest import *

We define a single simple model and a handler for the auto_create signal:

from lino.api import dd

class Tag(dd.Model):

    name = dd.CharField(max_length=100)

    def __str__(self):
        return self.name

def my_auto_create_handler(sender, **kw):
    print("My handler was called with {}".format(sender))
>>> from lino_book.projects.auto_create.models import Tag

Manually create a Tag:

>>> Tag(name="Foo").save()

A first call to lookup_or_create:

>>> Tag.lookup_or_create("name", "Foo")
Tag #1 ('Foo')

The signal was not emitted here because the Foo tag existed before.

>>> print(Tag.lookup_or_create("name", "Bar"))
My handler was called with Bar
>>> print(list(Tag.objects.all()))
[Tag #1 ('Foo'), Tag #2 ('Bar')]