Welcome | Get started | Dive | Contribute | Topics | Reference | Changes | More
lookup_or_create and the auto_create signal¶
This document describes and tests the
lookup_or_create
method and the
auto_create
signal.
Side note: Code snippets (lines starting with >>>
) in this document get
tested as part of our development workflow. The following
initialization snippet tells you which demo project is being used in
this document.
>>> 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
@dd.receiver(dd.auto_create)
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
Bar
>>> print(list(Tag.objects.all()))
[Tag #1 ('Foo'), Tag #2 ('Bar')]
Voilà.