django-modelcluster


Namedjango-modelcluster JSON
Version 6.3 PyPI version JSON
download
home_pagehttps://github.com/wagtail/django-modelcluster
SummaryDjango extension to allow working with 'clusters' of models as a single unit, independently of the database
upload_time2024-02-26 19:26:53
maintainer
docs_urlNone
authorMatthew Westcott
requires_python>=3.8
licenseBSD
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            django-modelcluster
===================

If you had a data model like this:

.. code-block:: python

 class Band(models.Model):
     name = models.CharField(max_length=255)

 class BandMember(models.Model):
     band = models.ForeignKey('Band', related_name='members', on_delete=models.CASCADE)
     name = models.CharField(max_length=255)


wouldn't it be nice if you could construct bundles of objects like this, independently of the database:

.. code-block:: python

 beatles = Band(name='The Beatles')
 beatles.members = [
     BandMember(name='John Lennon'),
     BandMember(name='Paul McCartney'),
 ]

Unfortunately, you can't. Objects need to exist in the database for foreign key relations to work:

.. code-block:: python

 IntegrityError: null value in column "band_id" violates not-null constraint

But what if you could? There are all sorts of scenarios where you might want to work with a 'cluster' of related objects, without necessarily holding them in the database: maybe you want to render a preview of the data the user has just submitted, prior to saving. Maybe you need to construct a tree of things, serialize them and hand them off to some external system. Maybe you have a workflow where your models exist in an incomplete 'draft' state for an extended time, or you need to handle multiple revisions, and you don't want to redesign your database around that requirement.

**django-modelcluster** extends Django's foreign key relations to make this possible. It introduces a new type of relation, *ParentalKey*, where the related models are stored locally to the 'parent' model until the parent is explicitly saved. Up to that point, the related models can still be accessed through a subset of the QuerySet API:

.. code-block:: python
 
 from modelcluster.models import ClusterableModel
 from modelcluster.fields import ParentalKey
 
 
 class Band(ClusterableModel):
     name = models.CharField(max_length=255)

 class BandMember(models.Model):
     band = ParentalKey('Band', related_name='members', on_delete=models.CASCADE)
     name = models.CharField(max_length=255)


 >>> beatles = Band(name='The Beatles')
 >>> beatles.members = [
 ...     BandMember(name='John Lennon'),
 ...     BandMember(name='Paul McCartney'),
 ... ]
 >>> [member.name for member in beatles.members.all()]
 ['John Lennon', 'Paul McCartney']
 >>> beatles.members.add(BandMember(name='George Harrison'))
 >>> beatles.members.count()
 3
 >>> beatles.save()  # only now are the records written to the database

For more examples, see the unit tests.


Many-to-many relations
----------------------

For many-to-many relations, a corresponding *ParentalManyToManyField* is available:

.. code-block:: python

 from modelcluster.models import ClusterableModel
 from modelcluster.fields import ParentalManyToManyField

 class Movie(ClusterableModel):
     title = models.CharField(max_length=255)
     actors = ParentalManyToManyField('Actor', related_name='movies')

 class Actor(models.Model):
     name = models.CharField(max_length=255)


 >>> harrison_ford = Actor.objects.create(name='Harrison Ford')
 >>> carrie_fisher = Actor.objects.create(name='Carrie Fisher')
 >>> star_wars = Movie(title='Star Wars')
 >>> star_wars.actors = [harrison_ford, carrie_fisher]
 >>> blade_runner = Movie(title='Blade Runner')
 >>> blade_runner.actors.add(harrison_ford)
 >>> star_wars.actors.count()
 2
 >>> [movie.title for movie in harrison_ford.movies.all()]  # the Movie records are not in the database yet
 []
 >>> star_wars.save()  # Star Wars now exists in the database (along with the 'actor' relations)
 >>> [movie.title for movie in harrison_ford.movies.all()]
 ['Star Wars']

Note that ``ParentalManyToManyField`` is defined on the parent model rather than the related model, just as a standard ``ManyToManyField`` would be. Also note that the related objects - the ``Actor`` instances in the above example - must exist in the database before being associated with the parent record. (The ``ParentalManyToManyField`` allows the relations between Movies and Actors to be stored in memory without writing to the database, but not the ``Actor`` records themselves.)


Introspection
-------------
If you need to find out which child relations exist on a parent model - to create a deep copy of the model and all its children, say - use the ``modelcluster.models.get_all_child_relations`` function:

.. code-block:: python

 >>> from modelcluster.models import get_all_child_relations
 >>> get_all_child_relations(Band)
 [<RelatedObject: tests:bandmember related to band>, <RelatedObject: tests:album related to band>]

This includes relations that are defined on any superclasses of the parent model.

To retrieve a list of all ParentalManyToManyFields defined on a parent model, use ``modelcluster.models.get_all_child_m2m_relations``:

.. code-block:: python

 >>> from modelcluster.models import get_all_child_m2m_relations
 >>> get_all_child_m2m_relations(Movie)
 [<modelcluster.fields.ParentalManyToManyField: actors>]

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/wagtail/django-modelcluster",
    "name": "django-modelcluster",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "",
    "author": "Matthew Westcott",
    "author_email": "matthew.westcott@torchbox.com",
    "download_url": "https://files.pythonhosted.org/packages/3d/dd/db1ab2e256f9fda6796ac312686561cbe2740d960c920f74410559ef7739/django-modelcluster-6.3.tar.gz",
    "platform": null,
    "description": "django-modelcluster\n===================\n\nIf you had a data model like this:\n\n.. code-block:: python\n\n class Band(models.Model):\n     name = models.CharField(max_length=255)\n\n class BandMember(models.Model):\n     band = models.ForeignKey('Band', related_name='members', on_delete=models.CASCADE)\n     name = models.CharField(max_length=255)\n\n\nwouldn't it be nice if you could construct bundles of objects like this, independently of the database:\n\n.. code-block:: python\n\n beatles = Band(name='The Beatles')\n beatles.members = [\n     BandMember(name='John Lennon'),\n     BandMember(name='Paul McCartney'),\n ]\n\nUnfortunately, you can't. Objects need to exist in the database for foreign key relations to work:\n\n.. code-block:: python\n\n IntegrityError: null value in column \"band_id\" violates not-null constraint\n\nBut what if you could? There are all sorts of scenarios where you might want to work with a 'cluster' of related objects, without necessarily holding them in the database: maybe you want to render a preview of the data the user has just submitted, prior to saving. Maybe you need to construct a tree of things, serialize them and hand them off to some external system. Maybe you have a workflow where your models exist in an incomplete 'draft' state for an extended time, or you need to handle multiple revisions, and you don't want to redesign your database around that requirement.\n\n**django-modelcluster** extends Django's foreign key relations to make this possible. It introduces a new type of relation, *ParentalKey*, where the related models are stored locally to the 'parent' model until the parent is explicitly saved. Up to that point, the related models can still be accessed through a subset of the QuerySet API:\n\n.. code-block:: python\n \n from modelcluster.models import ClusterableModel\n from modelcluster.fields import ParentalKey\n \n \n class Band(ClusterableModel):\n     name = models.CharField(max_length=255)\n\n class BandMember(models.Model):\n     band = ParentalKey('Band', related_name='members', on_delete=models.CASCADE)\n     name = models.CharField(max_length=255)\n\n\n >>> beatles = Band(name='The Beatles')\n >>> beatles.members = [\n ...     BandMember(name='John Lennon'),\n ...     BandMember(name='Paul McCartney'),\n ... ]\n >>> [member.name for member in beatles.members.all()]\n ['John Lennon', 'Paul McCartney']\n >>> beatles.members.add(BandMember(name='George Harrison'))\n >>> beatles.members.count()\n 3\n >>> beatles.save()  # only now are the records written to the database\n\nFor more examples, see the unit tests.\n\n\nMany-to-many relations\n----------------------\n\nFor many-to-many relations, a corresponding *ParentalManyToManyField* is available:\n\n.. code-block:: python\n\n from modelcluster.models import ClusterableModel\n from modelcluster.fields import ParentalManyToManyField\n\n class Movie(ClusterableModel):\n     title = models.CharField(max_length=255)\n     actors = ParentalManyToManyField('Actor', related_name='movies')\n\n class Actor(models.Model):\n     name = models.CharField(max_length=255)\n\n\n >>> harrison_ford = Actor.objects.create(name='Harrison Ford')\n >>> carrie_fisher = Actor.objects.create(name='Carrie Fisher')\n >>> star_wars = Movie(title='Star Wars')\n >>> star_wars.actors = [harrison_ford, carrie_fisher]\n >>> blade_runner = Movie(title='Blade Runner')\n >>> blade_runner.actors.add(harrison_ford)\n >>> star_wars.actors.count()\n 2\n >>> [movie.title for movie in harrison_ford.movies.all()]  # the Movie records are not in the database yet\n []\n >>> star_wars.save()  # Star Wars now exists in the database (along with the 'actor' relations)\n >>> [movie.title for movie in harrison_ford.movies.all()]\n ['Star Wars']\n\nNote that ``ParentalManyToManyField`` is defined on the parent model rather than the related model, just as a standard ``ManyToManyField`` would be. Also note that the related objects - the ``Actor`` instances in the above example - must exist in the database before being associated with the parent record. (The ``ParentalManyToManyField`` allows the relations between Movies and Actors to be stored in memory without writing to the database, but not the ``Actor`` records themselves.)\n\n\nIntrospection\n-------------\nIf you need to find out which child relations exist on a parent model - to create a deep copy of the model and all its children, say - use the ``modelcluster.models.get_all_child_relations`` function:\n\n.. code-block:: python\n\n >>> from modelcluster.models import get_all_child_relations\n >>> get_all_child_relations(Band)\n [<RelatedObject: tests:bandmember related to band>, <RelatedObject: tests:album related to band>]\n\nThis includes relations that are defined on any superclasses of the parent model.\n\nTo retrieve a list of all ParentalManyToManyFields defined on a parent model, use ``modelcluster.models.get_all_child_m2m_relations``:\n\n.. code-block:: python\n\n >>> from modelcluster.models import get_all_child_m2m_relations\n >>> get_all_child_m2m_relations(Movie)\n [<modelcluster.fields.ParentalManyToManyField: actors>]\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "Django extension to allow working with 'clusters' of models as a single unit, independently of the database",
    "version": "6.3",
    "project_urls": {
        "Homepage": "https://github.com/wagtail/django-modelcluster"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ee6d8deb2dfde2e1177412b759a1c32713be19b1d3af1da686e44e64c165e8c0",
                "md5": "13ab7a4c20a1917c3158c5e63fe52af3",
                "sha256": "a8783d6565a0663f41cd6003ea361c3a5711e8a2a326160f1ec1eceb3e973d4f"
            },
            "downloads": -1,
            "filename": "django_modelcluster-6.3-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "13ab7a4c20a1917c3158c5e63fe52af3",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": ">=3.8",
            "size": 29039,
            "upload_time": "2024-02-26T19:26:50",
            "upload_time_iso_8601": "2024-02-26T19:26:50.903225Z",
            "url": "https://files.pythonhosted.org/packages/ee/6d/8deb2dfde2e1177412b759a1c32713be19b1d3af1da686e44e64c165e8c0/django_modelcluster-6.3-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3ddddb1ab2e256f9fda6796ac312686561cbe2740d960c920f74410559ef7739",
                "md5": "cd85b042fa5842bb96c566fa869d9675",
                "sha256": "0caed8a0e889f3abb92f144670878a466ef954ffa6c4c7b9c80e6426b720a49d"
            },
            "downloads": -1,
            "filename": "django-modelcluster-6.3.tar.gz",
            "has_sig": false,
            "md5_digest": "cd85b042fa5842bb96c566fa869d9675",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 28903,
            "upload_time": "2024-02-26T19:26:53",
            "upload_time_iso_8601": "2024-02-26T19:26:53.185772Z",
            "url": "https://files.pythonhosted.org/packages/3d/dd/db1ab2e256f9fda6796ac312686561cbe2740d960c920f74410559ef7739/django-modelcluster-6.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-26 19:26:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "wagtail",
    "github_project": "django-modelcluster",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "django-modelcluster"
}
        
Elapsed time: 0.18772s