Welcome | Get started | Dive | Contribute | Topics | Reference | Changes | More

Introduction to generic foreign key fields

The GenericForeignKey field (GFK) is a great feature provided by Django’s contenttypes framework module. While a normal foreign key field can point to a database object of a given model, a generic foreign key can point to a database object of any model.

This page contains code snippets (lines starting with >>>), which are being tested during our development workflow. The following snippet initializes the demo project used throughout this page.

>>> from lino_book.projects.noi1r.startup import *

Usage example

The Comment is an example. A comment, in Lino, is always about a given “topic”, which is some other database row. And this database row can be on virtually any model.

How to use it

The gfks plugin does not define any model on its own, but it defines a widely used model mixin named Ownable.

In order to use GFKs, you must have the gfks plugin installed. Actually you probably already have it automatically installed if you install some other plugin that needs gfks. For example, if you say in your get_installed_plugins that you want the lino.modlib.comments plugin installed, this will automatically install lino.modlib.memo, which in turn will automatically install lino.modlib.gfks. So there are chances that you already have gfks already installed. And, by the way, the gfks in turn needs django.contrib.contenttypes.

>>> dd.plugins.comments.needs_plugins
['lino.modlib.memo']
>>> dd.plugins.memo.needs_plugins
['lino.modlib.office', 'lino.modlib.gfks']
>>> dd.plugins.gfks.needs_plugins
['lino.modlib.system', 'django.contrib.contenttypes']

Anyway, when you use a GeneriForeignKey field in your plugin, then you probably want to specify lino.modlib.gfks in your plugin’s needs_plugins attribute.

Special care when deleting database rows

In Lino you can configure the cascading behaviour from the model that defines the GFK, either by using the allow_cascaded_delete attribute or by defining a nullable GFK.

Lino’s disable_delete method tests for related objects, which automatically includes also those which are related using a GFK. non-nullable and warning before message.

GFK fields can break

The BrokenGFKs table.

More

Example for A tested example of GFK fields.

Old stuff? test_broken_gfks).