django-virtual-models


Namedjango-virtual-models JSON
Version 0.1.5 PyPI version JSON
download
home_pageNone
SummaryImprove performance and maintainability with a prefetching layer in your Django / Django REST Framework project
upload_time2023-05-29 19:31:43
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseNone
keywords django prefetch performance optimization
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <p align="center" style="margin: 0 0 10px">
  <img width="100" src="https://user-images.githubusercontent.com/397989/193950778-4550eebb-8650-45f8-8f57-d3bbab15e91a.svg" alt="Django Virtual Models Icon">
</p>
<p align="center">
  <strong>Django Virtual Models</strong>
</p>
<p align="center">
    <em>Improve performance and maintainability with a prefetching layer in your Django / Django REST Framework project</em>
</p>
<p align="center">
<a href="https://github.com/vintasoftware/django-virtual-models/actions?query=workflow%3ATest+event%3Apush+branch%3Amain" target="_blank">
    <img src="https://github.com/vintasoftware/django-virtual-models/workflows/tests/badge.svg?event=push&branch=main" alt="Test">
</a>&nbsp;
<a href="https://coveralls.io/github/vintasoftware/django-virtual-models?branch=main" target="_blank">
    <img src="https://coveralls.io/repos/github/vintasoftware/django-virtual-models/badge.svg?branch=main" alt="Coverage Status" />
</a>&nbsp;
<a href="https://pypi.org/project/django-virtual-models" target="_blank">
    <img src="https://img.shields.io/pypi/v/django-virtual-models?color=%2334D058&label=pypi%20package" alt="Package version">
</a>&nbsp;
<a href="https://pypi.org/project/django-virtual-models" target="_blank">
    <img src="https://img.shields.io/pypi/pyversions/django-virtual-models.svg?color=%2334D058" alt="Supported Python versions">
</a>
</p>

---

**Documentation**: <a href="https://vintasoftware.github.io/django-virtual-models/" target="_blank">https://vintasoftware.github.io/django-virtual-models/</a>

**Example project**: <a href="https://github.com/vintasoftware/django-virtual-models/tree/main/example" target="_blank">https://github.com/vintasoftware/django-virtual-models/tree/main/example</a>

**Source Code**: <a href="https://github.com/vintasoftware/django-virtual-models" target="_blank">https://github.com/vintasoftware/django-virtual-models</a>

---

Django Virtual Models introduces a new "prefetching layer" to Django codebases that assists developers to express complex read logic without sacrificing maintainability, composability and performance. A Virtual Model allows developers to declare all nesting they need along with all annotations, prefetches, and joins in a single declarative class.

When implementing Django REST Framework serializers, developers need to be careful to avoid causing the [*N+1 selects problem*](https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping) due to missing `prefetch_related` or `select_related` calls on the associated queryset. Additionaly, developers must not miss `annotate` calls for fields that are computed at queryset-level.

With Virtual Models integration with DRF, if you change a DRF Serializer, you won't forget to modify the associated queryset with additional annotations, prefetches, and joins. If you do forget to update the queryset, Django Virtual Models will guide you by raising friendly exceptions to assist you to write the correct Virtual Model for the serializer you're changing. This guidance will prevent N+1s and missing annotations in all serializers that use Virtual Models.

For example, imagine if you have following nested serializers starting from `MovieSerializer`:

```python
from movies.models import Nomination, Person, Movie

class AwardSerializer(serializers.ModelSerializer):
    class Meta:
        model = Nomination
        fields = ["award", "category", "year", "is_winner"]

class PersonSerializer(serializers.ModelSerializer):
    awards = AwardSerializer(many=True)
    nomination_count = serializers.IntegerField(read_only=True)

    class Meta:
        model = Person
        fields = ["name", "awards", "nomination_count"]

class MovieSerializer(serializers.ModelSerializer):
    directors = PersonSerializer(many=True)

    class Meta:
        model = Movie
        fields = ["name", "directors"]

```

For good performance and correct functionality, all nested serializers must have a corresponding `prefetch_related` on the queryset used by `MovieSerializer`. Also, the `nomination_count` field should be `annotate`d on it. Therefore, you'll need to write this complex chain of nested prefetches:

```python
from django.db.models import Prefetch

awards_qs = Nomination.objects.filter(is_winner=True)

directors_qs = Person.objects.prefetch_related(
    Prefetch(
        "nominations",
        queryset=awards_qs,
        to_attr="awards"
    )
).annotate(
    nomination_count=Count("nominations")
).distinct()

qs = Movie.objects.prefetch_related(
    Prefetch(
        "directors",
        queryset=directors_qs
    )
)
```

Conversely, you can declare Virtual Models for this read logic to easily reuse and customize those classes in multiple places of the codebase:

```python
import django_virtual_models as v

class VirtualAward(v.VirtualModel):
    class Meta:
        model = Nomination

    def get_prefetch_queryset(self, **kwargs):
        return Nomination.objects.filter(is_winner=True)


class VirtualPerson(v.VirtualModel):
    awards = VirtualAward(lookup="nominations")
    nomination_count = v.Annotation(
        lambda qs, **kwargs: qs.annotate(
            nomination_count=Count("nominations")
        ).distinct()
    )

    class Meta:
        model = Person


class VirtualMovie(v.VirtualModel):
    directors = VirtualPerson()

    class Meta:
        model = Movie
```

To configure your DRF view and serializer to use Virtual Models, inherit from the proper classes:

```python
import django_virtual_models as v

class MovieSerializer(v.VirtualModelSerializer):
    ...

    class Meta:
        ...
        virtual_model = VirtualMovie

class MovieList(v.VirtualModelListAPIView):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer
    ...
```

**Then the library will automatically do the right prefetches and annotations for you!**

If, for example, you forget to add the `nomination_count` field on `VirtualPerson`, the following exception will appear when using `MovieSerializer`:

![MissingVirtualModelFieldException exception](https://user-images.githubusercontent.com/397989/193944879-5205d80b-4102-415e-b178-7630a14db5a1.png)

If you aren't using DRF serializers, you hydrate your queryset with *virtual fields* manually:

```python
qs = VirtualMovie().get_optimized_queryset(
    Movie.objects.all(),
    lookup_list=[
        "directors__awards",
        "directors__nomination_count",
    ]
)
```

To learn more, check the [Installation](https://vintasoftware.github.io/django-virtual-models/installation/) and the [Tutorial](https://vintasoftware.github.io/django-virtual-models/tutorial/).
Or the [example project](https://github.com/vintasoftware/django-virtual-models/tree/main/example).

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "django-virtual-models",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "django,prefetch,performance,optimization",
    "author": null,
    "author_email": "\"Fl\u00e1vio Juvenal (Vinta Software)\" <flavio@vinta.com.br>",
    "download_url": "https://files.pythonhosted.org/packages/b0/e2/fc43e654a4b65540286c801954fa8fa90ebee1b72384e030c70e61127df9/django-virtual-models-0.1.5.tar.gz",
    "platform": null,
    "description": "<p align=\"center\" style=\"margin: 0 0 10px\">\n  <img width=\"100\" src=\"https://user-images.githubusercontent.com/397989/193950778-4550eebb-8650-45f8-8f57-d3bbab15e91a.svg\" alt=\"Django Virtual Models Icon\">\n</p>\n<p align=\"center\">\n  <strong>Django Virtual Models</strong>\n</p>\n<p align=\"center\">\n    <em>Improve performance and maintainability with a prefetching layer in your Django / Django REST Framework project</em>\n</p>\n<p align=\"center\">\n<a href=\"https://github.com/vintasoftware/django-virtual-models/actions?query=workflow%3ATest+event%3Apush+branch%3Amain\" target=\"_blank\">\n    <img src=\"https://github.com/vintasoftware/django-virtual-models/workflows/tests/badge.svg?event=push&branch=main\" alt=\"Test\">\n</a>&nbsp;\n<a href=\"https://coveralls.io/github/vintasoftware/django-virtual-models?branch=main\" target=\"_blank\">\n    <img src=\"https://coveralls.io/repos/github/vintasoftware/django-virtual-models/badge.svg?branch=main\" alt=\"Coverage Status\" />\n</a>&nbsp;\n<a href=\"https://pypi.org/project/django-virtual-models\" target=\"_blank\">\n    <img src=\"https://img.shields.io/pypi/v/django-virtual-models?color=%2334D058&label=pypi%20package\" alt=\"Package version\">\n</a>&nbsp;\n<a href=\"https://pypi.org/project/django-virtual-models\" target=\"_blank\">\n    <img src=\"https://img.shields.io/pypi/pyversions/django-virtual-models.svg?color=%2334D058\" alt=\"Supported Python versions\">\n</a>\n</p>\n\n---\n\n**Documentation**: <a href=\"https://vintasoftware.github.io/django-virtual-models/\" target=\"_blank\">https://vintasoftware.github.io/django-virtual-models/</a>\n\n**Example project**: <a href=\"https://github.com/vintasoftware/django-virtual-models/tree/main/example\" target=\"_blank\">https://github.com/vintasoftware/django-virtual-models/tree/main/example</a>\n\n**Source Code**: <a href=\"https://github.com/vintasoftware/django-virtual-models\" target=\"_blank\">https://github.com/vintasoftware/django-virtual-models</a>\n\n---\n\nDjango Virtual Models introduces a new \"prefetching layer\" to Django codebases that assists developers to express complex read logic without sacrificing maintainability, composability and performance. A Virtual Model allows developers to declare all nesting they need along with all annotations, prefetches, and joins in a single declarative class.\n\nWhen implementing Django REST Framework serializers, developers need to be careful to avoid causing the [*N+1 selects problem*](https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping) due to missing `prefetch_related` or `select_related` calls on the associated queryset. Additionaly, developers must not miss `annotate` calls for fields that are computed at queryset-level.\n\nWith Virtual Models integration with DRF, if you change a DRF Serializer, you won't forget to modify the associated queryset with additional annotations, prefetches, and joins. If you do forget to update the queryset, Django Virtual Models will guide you by raising friendly exceptions to assist you to write the correct Virtual Model for the serializer you're changing. This guidance will prevent N+1s and missing annotations in all serializers that use Virtual Models.\n\nFor example, imagine if you have following nested serializers starting from `MovieSerializer`:\n\n```python\nfrom movies.models import Nomination, Person, Movie\n\nclass AwardSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = Nomination\n        fields = [\"award\", \"category\", \"year\", \"is_winner\"]\n\nclass PersonSerializer(serializers.ModelSerializer):\n    awards = AwardSerializer(many=True)\n    nomination_count = serializers.IntegerField(read_only=True)\n\n    class Meta:\n        model = Person\n        fields = [\"name\", \"awards\", \"nomination_count\"]\n\nclass MovieSerializer(serializers.ModelSerializer):\n    directors = PersonSerializer(many=True)\n\n    class Meta:\n        model = Movie\n        fields = [\"name\", \"directors\"]\n\n```\n\nFor good performance and correct functionality, all nested serializers must have a corresponding `prefetch_related` on the queryset used by `MovieSerializer`. Also, the `nomination_count` field should be `annotate`d on it. Therefore, you'll need to write this complex chain of nested prefetches:\n\n```python\nfrom django.db.models import Prefetch\n\nawards_qs = Nomination.objects.filter(is_winner=True)\n\ndirectors_qs = Person.objects.prefetch_related(\n    Prefetch(\n        \"nominations\",\n        queryset=awards_qs,\n        to_attr=\"awards\"\n    )\n).annotate(\n    nomination_count=Count(\"nominations\")\n).distinct()\n\nqs = Movie.objects.prefetch_related(\n    Prefetch(\n        \"directors\",\n        queryset=directors_qs\n    )\n)\n```\n\nConversely, you can declare Virtual Models for this read logic to easily reuse and customize those classes in multiple places of the codebase:\n\n```python\nimport django_virtual_models as v\n\nclass VirtualAward(v.VirtualModel):\n    class Meta:\n        model = Nomination\n\n    def get_prefetch_queryset(self, **kwargs):\n        return Nomination.objects.filter(is_winner=True)\n\n\nclass VirtualPerson(v.VirtualModel):\n    awards = VirtualAward(lookup=\"nominations\")\n    nomination_count = v.Annotation(\n        lambda qs, **kwargs: qs.annotate(\n            nomination_count=Count(\"nominations\")\n        ).distinct()\n    )\n\n    class Meta:\n        model = Person\n\n\nclass VirtualMovie(v.VirtualModel):\n    directors = VirtualPerson()\n\n    class Meta:\n        model = Movie\n```\n\nTo configure your DRF view and serializer to use Virtual Models, inherit from the proper classes:\n\n```python\nimport django_virtual_models as v\n\nclass MovieSerializer(v.VirtualModelSerializer):\n    ...\n\n    class Meta:\n        ...\n        virtual_model = VirtualMovie\n\nclass MovieList(v.VirtualModelListAPIView):\n    queryset = Movie.objects.all()\n    serializer_class = MovieSerializer\n    ...\n```\n\n**Then the library will automatically do the right prefetches and annotations for you!**\n\nIf, for example, you forget to add the `nomination_count` field on `VirtualPerson`, the following exception will appear when using `MovieSerializer`:\n\n![MissingVirtualModelFieldException exception](https://user-images.githubusercontent.com/397989/193944879-5205d80b-4102-415e-b178-7630a14db5a1.png)\n\nIf you aren't using DRF serializers, you hydrate your queryset with *virtual fields* manually:\n\n```python\nqs = VirtualMovie().get_optimized_queryset(\n    Movie.objects.all(),\n    lookup_list=[\n        \"directors__awards\",\n        \"directors__nomination_count\",\n    ]\n)\n```\n\nTo learn more, check the [Installation](https://vintasoftware.github.io/django-virtual-models/installation/) and the [Tutorial](https://vintasoftware.github.io/django-virtual-models/tutorial/).\nOr the [example project](https://github.com/vintasoftware/django-virtual-models/tree/main/example).\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Improve performance and maintainability with a prefetching layer in your Django / Django REST Framework project",
    "version": "0.1.5",
    "project_urls": {
        "Documentation": "https://vintasoftware.github.io/django-virtual-models/",
        "Homepage": "https://github.com/vintasoftware/django-virtual-models"
    },
    "split_keywords": [
        "django",
        "prefetch",
        "performance",
        "optimization"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8e55af0c1a916638a9bf6773bc85f000a19b2e00dd0b3c70ebbef10cfc923376",
                "md5": "120021b586ffd7ca21f7d8ff6dfda781",
                "sha256": "e52c0b7b362b5bfe88fd58536f7c36c3bf1baef3e49070e0cc80b2f15b97d7b4"
            },
            "downloads": -1,
            "filename": "django_virtual_models-0.1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "120021b586ffd7ca21f7d8ff6dfda781",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 21400,
            "upload_time": "2023-05-29T19:31:40",
            "upload_time_iso_8601": "2023-05-29T19:31:40.669599Z",
            "url": "https://files.pythonhosted.org/packages/8e/55/af0c1a916638a9bf6773bc85f000a19b2e00dd0b3c70ebbef10cfc923376/django_virtual_models-0.1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b0e2fc43e654a4b65540286c801954fa8fa90ebee1b72384e030c70e61127df9",
                "md5": "c36138da3c7aed28ddb2f5fc38e18270",
                "sha256": "47af744c2fd28800a244985bfeef89d4fc4365b239552276fc74274ea9871ec0"
            },
            "downloads": -1,
            "filename": "django-virtual-models-0.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "c36138da3c7aed28ddb2f5fc38e18270",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 52018,
            "upload_time": "2023-05-29T19:31:43",
            "upload_time_iso_8601": "2023-05-29T19:31:43.533499Z",
            "url": "https://files.pythonhosted.org/packages/b0/e2/fc43e654a4b65540286c801954fa8fa90ebee1b72384e030c70e61127df9/django-virtual-models-0.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-29 19:31:43",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "vintasoftware",
    "github_project": "django-virtual-models",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-virtual-models"
}
        
Elapsed time: 1.23966s