django-loose-fk

Django Loose FK handles local or remote "ForeignKey" references.


Keywords
ForeignKey, URL, reference, decentralization, integrity
License
MIT
Install
pip install django-loose-fk==0.7.0

Documentation

Django Loose FK

Version

1.0.4

Source

https://github.com/maykinmedia/django-loose-fk

Keywords

ForeignKey, URL reference, decentralization, integrity

Build status Code quality checks black Coverage status

python-versions django-versions pypi-version

Django Loose FK handles local or remote "ForeignKey" references.

In a decentralized API landscape various providers can offer the same type of data, while your own API also provides this. The django model field allows you to handle this transparently and present a unified, clean Python API.

Features

  • Always work with Django model instances
  • Automatically added check constraints
  • Pluggable interface to fetch remote objects
  • Automatically supports DRF Hyperlinked serializers and serializer fields

Installation

Requirements

  • Python 3.7 or above
  • setuptools 30.3.0 or above
  • Django 3.2 or newer

Install

Warning

You must also make sure ALLOWED_HOSTS is a list of actual domains, and not a wildcard. When loose-fk gets a URL to load, it first looks up if the domain is a local domain and if so, will load the actual local database record.

Usage

At the core sits a (virtual) django model field.

You can now create objects with either local instances or URLs:

Accessing the attribute will always yield an instance:

In the case of a remote URL, the URL will be fetched and the JSON response used as init kwargs for a model instance. The .save() method is blocked for remote instances to prevent mistakes.

Loaders

Loaders are pluggable interfaces to load data. The default loader is django_loose_fk.loaders.RequestsLoader, which depends on the requests library to fetch the data.

You can specify a global default loader with the setting DEFAULT_LOOSE_FK_LOADER

or override the loader on a per-field basis:

Local and remote urls

If several services are hosted within the same domain, it could be tricky to separate local and remote urls. In this case an additional setting LOOSE_FK_LOCAL_BASE_URLS can be used to define an explicit list of allowed prefixes for local urls.