dj-drf-utils


Namedj-drf-utils JSON
Version 1.2.0 PyPI version JSON
download
home_pagehttps://github.com/cayo-rodrigues/django-utils
SummaryUseful functions and classes for Django and Django Rest Framework
upload_time2022-09-18 22:24:17
maintainer
docs_urlNone
authorCayo Rodrigues
requires_python>=3.8
licenseMIT
keywords django utils serializers generic views viewsets mixins email login model manager custom action shortcut error simple rest framework dj drf admin hash password user
VCS
bugtrack_url
requirements asgiref bleach certifi cffi charset-normalizer commonmark cryptography Django djangorestframework docutils idna importlib-metadata jeepney keyring pkginfo pycparser Pygments pytz readme-renderer requests requests-toolbelt rfc3986 rich SecretStorage six sqlparse twine urllib3 webencodings zipp
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # dj-drf-utils

This package provides useful functions and classes to be used in [Django](https://www.djangoproject.com/) projects, specially when working with [Django Rest Framework](https://www.django-rest-framework.org/). Below are some further explation about how to use this package and what each module inside it does.

The examples on this documentation are about movies and cinemas, having entities like `Movie`, `Cinema`, `Room`, and `MovieSession`.

## Installation

First, run:

```bash
pip install dj-drf-utils
```

That's it!

## helpers.py

This module provides three useful functions. Two of them are a more powerful and versatille version of `get_object_or_404` and `get_list_or_404`, and the other is a handy shortcut.

### get_object_or_error

Almost the same as `django.shortcuts.get_object_or_404`, but can raise any
custom error class you want, allowing you to return more precise error messages.
Another advantage of using this helper function, is that it prevents your application
from crashing. For instance, in case you want to get an object by it's primary key, and
it is of type `uuid`, but another data type is provided in the url, it will not crash,
unlike the standard `get_object_or_404`. It expects the following arguments:

- `klass` -> The model that will be used for the query
- `exception` -> An error class inheriting from `rest_framework.exceptions.APIException`.
If no `exception` is provided, then the standard `django.http.Http404` class is used.
- `**kwargs` -> Keyword arguments representing all fields that should be used for the
search, as many as you please.

For instance, in case you want to get a `Room` of a `Cinema`:

```python
# exceptions.py

from rest_framework.exceptions import APIException, status


class CinemaNotFoundError(APIException):
    status_code = status.HTTP_404_NOT_FOUND
    default_detail = "Cinema not found"


class RoomNotFoundError(APIException):
    status_code = status.HTTP_404_NOT_FOUND
    default_detail = "Room not found in this cinema"
```

```python
# request endpoint

"/cinemas/<cinema_id>/rooms/<room_id>/"
```

```python
# views.py

from dj_drf_utils.helpers import get_object_or_error


cinema = get_object_or_error(Cinema, CinemaNotFoundError, pk=self.kwargs['cinema_id'])
room = get_object_or_error(Room, RoomNotFoundError, pk=self.kwargs['room_id'], cinema=cinema)
```

Note that in case a room id is valid, but the cinema id is not, an appropriated message will be
returned. In case you would use `get_object_or_404`, you would get just a `"Not found."`. Having
more than one lookup field, `get_object_or_error` makes much clearer what is the problem.

I highly encorage you to have a quick look at the source code, it's quite a simple concept.

---

### get_list_or_error

Almost the same as `django.shortcuts.get_list_or_404`, but can raise any
custom error class you want, allowing you to return more precise error messages.
Another advantage of using this helper function, is that it prevents your application
from crashing. For instance, in case you want to get a list, filtering it by some foreign
key field, which is of type `uuid`, but another data type is provided in the url, it will
not crash, unlike the standard `get_list_or_404`. Also, this function gives you the possiblity
of not raising an exception when no values are found, so you could just return an empty list.
It expects the following arguments:

- `klass` -> The model that will be used for the query
- `exception` -> An error class inheriting from `rest_framework.exceptions.APIException`.
If no `exception` is provided, then the standard `django.http.Http404` class is used.
- `accept_empty` -> A boolean argument, which defaults to `False`. When provided, determines
if an empty result is acceptable or if it should raise `exception`.
- `**kwargs` -> Keyword arguments representing all fields that should be used for the
search, as many as you please.

For instance, in case you want to list all `MovieSession`s of a `Room` in a `Cinema`:

```python
# exceptions.py

from rest_framework.exceptions import APIException, status


class NoMovieSessionsError(APIException):
    status_code = status.HTTP_404_NOT_FOUND
    default_detail = "This room has no scheduled movie sessions"
```

```python
# request endpoint

"/cinemas/<cinema_id>/rooms/<room_id>/movie-sessions/"
```

```python
# views.py

from dj_drf_utils.helpers import get_object_or_error, get_list_or_error


cinema = get_object_or_error(Cinema, CinemaNotFoundError, pk=self.kwargs['cinema_id'])
room = get_object_or_error(Room, RoomNotFoundError, pk=self.kwargs['room_id'], cinema=cinema)
movie_sessions = get_list_or_error(MovieSession, NoMovieSessionsError, room=room)
```

I highly encorage you to have a quick look at the source code, it's quite a simple concept.

---

### set_and_destroy

This function basically sets a new list of values in a foreign key field and erases any
previous values that were related to `klass`. For it to work, **you must set `null=True`
in your model**, otherwise, the values will not be subsitituted, they will only be added.
It accepts the following parameters:

- `klass` -> The model on the side `1` of a `1:N` relationship, the owner of the relation,
in which the new values will be set
- `attr` -> A string version of the attribute corresponding to the `related_name` value
in the foreign key field
- `value` -> A list (or any other iterable), containing new created instances of `related_klass`
- `related_klass` -> The model on the side `N` of a `1:N` relationship, the one having the foreign
key field
- `**kwargs` -> Keyword arguments used in a filter to determine which objects should be destroyed.
It could be really anything, but usually you will want it to be something like `klass=None`, so
that all objects that are no part of the relationship anymore can be descarded.

For instance, a `Movie` may have many `Video`s related to it, like teasers and trailers. In case
you want to update a `Movie`, reseting its `Video`s:

```python
# models.py

class Movie(models.Model):
    ...


class Video(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
    title = models.CharField(max_length=127)
    url = models.URLField()

    movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name="videos", null=True)
```

```python
# serializers.py

from dj_drf_utils.helpers import set_and_destroy


class MovieSerializer(serializers.ModelSerializer):
    ...

    def update(self, instance: Movie, validated_data: dict):
      ...

      videos_data = validated_data.pop("videos", None)
      if videos_data:
          videos = [
            Video.get_or_create(**video, movie=instance)[0]
            for video in videos_data
          ]
          set_and_destroy(
              klass=instance,
              attr="videos",
              value=videos,
              related_klass=Video,
              movie=None,
          )
```

In the example above, we are first getting or creating video instances, in order to reuse the ones
passed in the body of the request that may already be in our db. Each video can only be related to
one movie, since it doesn't make sense that two movies have the same trailer or teaser. So when
assigning this new list of videos to a movie, the `set_and_destroy` function safely deletes all
videos having their `movie` foreign key equal to `None`.

I highly encorage you to have a quick look at the source code, it's quite a simple concept.

---

### bulk_get_or_create

Despite the name of this function, it does not translate into a single database hit,
unfortunatelly. But it is still better than a loop executing `Model.objects.get_or_create`
in every iteration.

That's because this function **combines filters and the bulk_create method**.
Django querysets are lazy, but in this function they are evaluated on every iteration.
However, in the end **only one** `INSERT` query is performed.

---

#### Important!
Django's `Model.objects.bulk_create` method returns a list of newly created instances **without ids**
when working with SQLite. Please, make sure to use PostgreSQL to avoid problems.

---

It expects the following parameters:

- `klass` -> The model whose values will be retrieved or created
- `values` -> A list of dictionaries having key value pairs demanded by `klass`
- `only_create` -> A boolean value. Defaults to `False`. In case you don't care about getting
existing values, and just wants to create them, then you can set this arguments to `True`. It
will result in just one database hit.
- `kwargs` -> Key value pairs with extra fields you want to use for filtering/creating instances
of `klass`. It can be useful for foreign key fields

Usage example:

```python
# serializers.py

from dj_drf_utils.helpers import bulk_get_or_create, set_and_destroy


class MovieSerializer(serializers.ModelSerializer):
    # ...

    def create(self, validated_data: dict) -> Movie:
        # ...

        videos_data = validated_data.pop("videos")

        # ...

        bulk_get_or_create(Video, videos_data, movie=movie)

        # ...

    def update(self, instance: Movie, validated_data: dict) -> Movie:
        # ...

        videos = validated_data.pop("videos", None)

        # ...

        if videos:
            set_and_destroy(
                klass=instance,
                attr="videos",
                value=bulk_get_or_create(Video, videos, movie=instance),
                related_klass=Video,
                movie=None,
            )

        # ...
```

Note that in the `update` method, we are combining `set_and_destroy` with `bulk_get_or_create`.
That's totally a thing.

I highly encourage you to have a look at the source code, so that you can better understand what's
happening under the hood. It's not complicated.


## mixins.py

This module provides useful mixins to be used in Django Rest Framework **generic views** and **viewsets**.

### SerializerByMethodMixin

This mixin overrides the `get_serializer_class` method of generic views. It's
purpose is to dinamically define which serializer to use, depending on the request
method. For this to be possible, a new class property should be set, it is:

- `method_serializers` -> It should be a dictionary having it's keys with the names
of http methods and values as the serializer classes corresponding to each method.
If the request method does not match any of the dict keys, it will return the value
of `self.serializer_class`.

Below is an example:

```python
# views.py

from dj_drf_utils.mixins import SerializerByMethodMixin


class MyBeautifulGenericView(SerializerByMethodMixin, ListCreateAPIView):
    queryset = MyWonderfulModel.objects.all()
    serializer_class = MyDefaultSerializer
    method_serializers = {
        "GET": MySerialzerToUseInGetRequests,
    }
```

---

### SerializerByActionMixin

This mixin overrides the `get_serializer_class` method of viewsets. It's
purpose is to dinamically define which serializer to use, depending on the viewset
action. For this to be possible, a new class property should be set, it is:

- `action_serializers` -> It should be a dictionary having it's keys with the names
of viewset actions and values as the serializer classes corresponding to each action.
If the viewset action does not match any of the dict keys, it will return the value
of `self.serializer_class`.

Below is an example:

```python
# views.py

from dj_drf_utils.mixins import SerializerByActionMixin


class MyBeautifulViewSet(SerializerByActionMixin, ModelViewSet):
    queryset = MyWonderfulModel.objects.all()
    serializer_class = MyDefaultSerializer
    action_serializers = {
        "create": MySerializerToUseInCreateActions,
        "update": MySerialzerToUseInUpdateActions,
        "partial_update": MySerialzerToUseInPartialUpdateActions,
    }
```

---

### SerializerByDetailActionsMixin

This mixin overrides the `get_serializer_class` method of viewsets. It's
purpose is to dinamically define which serializer to use, depending on the viewset
action. If it is a detail action, that is, one of `retrieve`, `update`, `partial_update`
and `destroy`, then `self.detail_serializer_class` will be returned. Else, the default
`self.serializer_class` is used. For this to be possible, a new class property should
be set, it is:

- `detail_serializer_class` -> It's value should be a serializer class. This property defines
which serializer to use in detail actions.

Below is an example:

```python
# views.py

from dj_drf_utils.mixins import SerializerByDetailActionsMixin


class MyBeautifulViewSet(SerializerByDetailActionsMixin, ModelViewSet):
    queryset = MyWonderfulModel.objects.all()
    serializer_class = MyDefaultSerializer
    detail_serializer_class = MyDetailSerializer
```

---

### SerializerBySafeActionsMixin

This mixin overrides the `get_serializer_class` method of viewsets. It's
purpose is to dinamically define which serializer to use, depending on the viewset
action. If it is a _safe action_, then `self.safe_serializer_class` will be returned.
Else, the default `self.serializer_class` is returned. A safe action is an action
listed in the `safe_actions` class property. For this to be possible, a new class
property should be set, it is:

- `safe_serializer_class` -> Its value should be a serializer class. This property defines
which serializer to use in safe actions.

You can totally customize what is a "safe action". For that, you could change the value
of `self.safe_actions`.

- `safe_actions` -> It should be a `list[str]`, which each item representing a viewset action,
considered safe for that viewset. The default value is `["list", "retrieve"]`

Below is an example:

```python
# views.py

from dj_drf_utils.mixins import SerializerBySafeActionsMixin


class MyBeautifulViewSet(SerializerBySafeActionsMixin, ModelViewSet):
    queryset = MyWonderfulModel.objects.all()
    serializer_class = MyDefaultSerializer
    safe_serializer_class = MySafeSerializer
```

## managers.py

This module provides a custom user manager as a shortcut for whoever wants to customize
django's authentication system to use a different field instead of username for login.
It can be really anything, like email, phone, cpf, etc.

### CustomUserManager

A custom user manager that inherits from `django.contrib.auth.models.BaseUserManager`.
Its purpouse in life is mainly to provide an easy and simple way to implement a login
and register system that expects another field instead of `username`.

But what if you desired to customize your users in a way that other info is also required
for user creation? No problem, this class is highly customizable.

Instead of having to override the `create` and `create_superuser` methods of `BaseUserManager`,
you can inherit from `CustomUserManager` and then simply set some class properties at your will.
They work as follows:

- `auth_field_name` -> Defaults to `"email"`. Defines what is the name of the field that
should be used for login (besides password, of course). Note that this field **must**
exist in your user model, **having a unique constraint**.
- `user_is_staff` -> Defaults to `False`. Defines the starting staff status of newly
created users
- `user_start_active` -> Defaults to `True`. Defines if a user account should start in
active state. In cases where users have to confirm their account in some way before getting
access, you may wish to set this property to `False`
- `super_is_staff` -> Defaults to `True`. Defines the starting staff status of newly
created superusers
- `super_start_active` -> Defaults to `True`. Defines if a superuser account should start in
active state. Usually you'll want this value to be `True`, but you're totally free to change
it, depending on your needs.
- `required_fields` -> Defaults to `[]`. It should be a `list[str]`. This property defines
which fields are required to be provided upon user creation, besides `self.auth_field_name` and
`password`. The fields `is_staff`, `is_superuser` and `is_active` should also not be present in
this list. It is worth noting that **all fields defined here, must also be defined in your user model**.
Otherwise, a `ValidationError` is raised.

Below is an example of how you may customize the behaviour of this class:

```python
# managers.py

from dj_drf_utils.managers import CustomUserManager


class MyOwnUserManager(CustomUserManager):
    user_start_active = False
    required_fields = ["first_name", "last_name"]
```

In order to implement a login with email feature, for instance, you have to make some minor
changes to your user model. Below are some settings that may come in handy for you to define
in your model:

```python
# models.py

from .managers import MyOwnUserManager
from django.db import models
from django.contrib.auth.models import AbstractUser


class MyUser(AbstractUser):
    email = models.EmailField(unique=True)

    username = None

    objects = MyOwnUserManager()

    USERNAME_FIELD = objects.auth_field_name
    REQUIRED_FIELDS = objects.required_fields
```

The `email` property is defined as unique, since it's gonna be used for login (as per the `USERNAME_FIELD`
property). The `objects` property may be either the standard `dj_drf_utils.managers.CustomUserManager`
or your own manager that inherits from it. In the example above, we are using our own user manager,
with some minor customizations. `REQUIRED_FIELDS` refer to the fields you are prompted when creating a
superuser (it must not include the value defined for `USERNAME_FIELD` or `"password"`). Defining it to
`objects.required_fields` prevents you from making mistakes and being redundant. Note that in the example
above we are droping the `username` column, but that's not necessary if you still want to have a username
in your user model.


## action_patterns.py

Viewsets have the advantage of abstracting away the work of defining routes explicitly,
but routers have some limits. They can only go to a certain depth in producing urls.

For instance, let's imagine a simple application, where you have Bands and Albums.
In case you wish to list all Albums of a Band, you could make a request to an enpoint
like `/bands/<band_id>/albums/`. That's totally possible with routers. But what if you
want a detail route for an Album of a Band? A route like `/bands/<band_id>/albums/<album_id>/`
would make sense, right? But routers aren't able to go to such an extent. And you could
totally imagine bigger urls in real, bigger applications.

So defining our routes manually gives us a lot more control. Everything comes with a tradeoff
though. When manually defining routes for generic views, you can easily assign each view class
to their routes, using the `as_view` method. But viewsets are different. One viewset class can
be assigned to more than one route. So for that to work, you've gotta do something like [this](https://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/#binding-viewsets-to-urls-explicitly).

In order to simplify things, and abstract away some boiler plate code, this module provides the
standard viewset actions mapped to their corresponding http method. Of course, you may have additional
actions, customized according to your own needs. In this case, you can config them on your own. But
the standard ones are all set here.

Usage example:

```python
# urls.py

from django.urls import path
from dj_drf_utils.action_patterns import STANDARD_DETAIL_PATTERN, STANDARD_PATTERN

from . import views


cinema_view = views.CinemaViewSet.as_view(STANDARD_PATTERN)
cinema_detail_view = views.CinemaViewSet.as_view(STANDARD_DETAIL_PATTERN)

urlpatterns = [
    path("", cinema_view),
    path("<cinema_id>/", cinema_detail_view),
]
```

But routers are still so cool and so simple to use. So a very good alternative is [drf-nested-routers](https://github.com/alanjds/drf-nested-routers).
It really makes it easier to deal with all of this. The `drf-nested-routers` library is designed to
solve exactly this problem, and even more.


## admin.py

This module provides a `CustomUserAdmin` class. It inherits from `django.contrib.auth.admin.UserAdmin`.
Have you ever created a custom user model, added it to admin and then realized that your users passwords
were being created unhashed? Then you searched the internet and found out that django provides a `UserAdmin`
class that does the job. But what if you customized your authentication system, and you're using another
field instead of `username`? In this case, it throws an error, saying that there is no `username` field.

In order to make things easier, this module provides a class that abstracts away all the boring 
configurations you would need to do.

### CustomUserAdmin

This class inherits from `django.contrib.auth.admin.UserAdmin`. It's purpose in life is to abstract
away some boring configurations you may need, when you're using a custom user model. The advantage is
to have the same features that Django standard `UserAdmin` class provides, but in a custom user model,
having a field other than `username` used for authentication.

This class automaticaly figures out what is your user model, as long as it is pointed to by `AUTH_USER_MODEL`
setting in `settings.py`. Also, it takes the care of first checking for the fields you set in your user
model before referencing them. But the **password field is mandatory**.

Below is an usage example:

```python
# admin.py

from dj_drf_utils.admin import CustomUserAdmin
from .models import User

admin.site.register(User, CustomUserAdmin)
```

In case you want to customize some kind of behaviour, you totally can, but you will have to overwrite the
properties entirely. For instance, if you need to change the columns of `list_display`, you could do something
like this:

```python

# admin.py

from dj_drf_utils.admin import CustomUserAdmin
from .models import User

class MyOwnUserAdmin(CustomUserAdmin):
    list_display = ['id', 'email', 'first_name', 'last_name', 'birth_date', 'is_staff', 'is_superuser']

admin.site.register(User, MyOwnUserAdmin)
```

Not so bad.


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/cayo-rodrigues/django-utils",
    "name": "dj-drf-utils",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "django utils serializers generic views viewsets mixins email login model manager custom action shortcut error simple rest framework dj drf admin hash password user",
    "author": "Cayo Rodrigues",
    "author_email": "cayo.rodrigues1914@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/74/e6/c171562eb3f23a9347e337bb416e2053f945660a3cf78ba9e91ab60c5f3c/dj_drf_utils-1.2.0.tar.gz",
    "platform": null,
    "description": "# dj-drf-utils\n\nThis package provides useful functions and classes to be used in [Django](https://www.djangoproject.com/) projects, specially when working with [Django Rest Framework](https://www.django-rest-framework.org/). Below are some further explation about how to use this package and what each module inside it does.\n\nThe examples on this documentation are about movies and cinemas, having entities like `Movie`, `Cinema`, `Room`, and `MovieSession`.\n\n## Installation\n\nFirst, run:\n\n```bash\npip install dj-drf-utils\n```\n\nThat's it!\n\n## helpers.py\n\nThis module provides three useful functions. Two of them are a more powerful and versatille version of `get_object_or_404` and `get_list_or_404`, and the other is a handy shortcut.\n\n### get_object_or_error\n\nAlmost the same as `django.shortcuts.get_object_or_404`, but can raise any\ncustom error class you want, allowing you to return more precise error messages.\nAnother advantage of using this helper function, is that it prevents your application\nfrom crashing. For instance, in case you want to get an object by it's primary key, and\nit is of type `uuid`, but another data type is provided in the url, it will not crash,\nunlike the standard `get_object_or_404`. It expects the following arguments:\n\n- `klass` -> The model that will be used for the query\n- `exception` -> An error class inheriting from `rest_framework.exceptions.APIException`.\nIf no `exception` is provided, then the standard `django.http.Http404` class is used.\n- `**kwargs` -> Keyword arguments representing all fields that should be used for the\nsearch, as many as you please.\n\nFor instance, in case you want to get a `Room` of a `Cinema`:\n\n```python\n# exceptions.py\n\nfrom rest_framework.exceptions import APIException, status\n\n\nclass CinemaNotFoundError(APIException):\n    status_code = status.HTTP_404_NOT_FOUND\n    default_detail = \"Cinema not found\"\n\n\nclass RoomNotFoundError(APIException):\n    status_code = status.HTTP_404_NOT_FOUND\n    default_detail = \"Room not found in this cinema\"\n```\n\n```python\n# request endpoint\n\n\"/cinemas/<cinema_id>/rooms/<room_id>/\"\n```\n\n```python\n# views.py\n\nfrom dj_drf_utils.helpers import get_object_or_error\n\n\ncinema = get_object_or_error(Cinema, CinemaNotFoundError, pk=self.kwargs['cinema_id'])\nroom = get_object_or_error(Room, RoomNotFoundError, pk=self.kwargs['room_id'], cinema=cinema)\n```\n\nNote that in case a room id is valid, but the cinema id is not, an appropriated message will be\nreturned. In case you would use `get_object_or_404`, you would get just a `\"Not found.\"`. Having\nmore than one lookup field, `get_object_or_error` makes much clearer what is the problem.\n\nI highly encorage you to have a quick look at the source code, it's quite a simple concept.\n\n---\n\n### get_list_or_error\n\nAlmost the same as `django.shortcuts.get_list_or_404`, but can raise any\ncustom error class you want, allowing you to return more precise error messages.\nAnother advantage of using this helper function, is that it prevents your application\nfrom crashing. For instance, in case you want to get a list, filtering it by some foreign\nkey field, which is of type `uuid`, but another data type is provided in the url, it will\nnot crash, unlike the standard `get_list_or_404`. Also, this function gives you the possiblity\nof not raising an exception when no values are found, so you could just return an empty list.\nIt expects the following arguments:\n\n- `klass` -> The model that will be used for the query\n- `exception` -> An error class inheriting from `rest_framework.exceptions.APIException`.\nIf no `exception` is provided, then the standard `django.http.Http404` class is used.\n- `accept_empty` -> A boolean argument, which defaults to `False`. When provided, determines\nif an empty result is acceptable or if it should raise `exception`.\n- `**kwargs` -> Keyword arguments representing all fields that should be used for the\nsearch, as many as you please.\n\nFor instance, in case you want to list all `MovieSession`s of a `Room` in a `Cinema`:\n\n```python\n# exceptions.py\n\nfrom rest_framework.exceptions import APIException, status\n\n\nclass NoMovieSessionsError(APIException):\n    status_code = status.HTTP_404_NOT_FOUND\n    default_detail = \"This room has no scheduled movie sessions\"\n```\n\n```python\n# request endpoint\n\n\"/cinemas/<cinema_id>/rooms/<room_id>/movie-sessions/\"\n```\n\n```python\n# views.py\n\nfrom dj_drf_utils.helpers import get_object_or_error, get_list_or_error\n\n\ncinema = get_object_or_error(Cinema, CinemaNotFoundError, pk=self.kwargs['cinema_id'])\nroom = get_object_or_error(Room, RoomNotFoundError, pk=self.kwargs['room_id'], cinema=cinema)\nmovie_sessions = get_list_or_error(MovieSession, NoMovieSessionsError, room=room)\n```\n\nI highly encorage you to have a quick look at the source code, it's quite a simple concept.\n\n---\n\n### set_and_destroy\n\nThis function basically sets a new list of values in a foreign key field and erases any\nprevious values that were related to `klass`. For it to work, **you must set `null=True`\nin your model**, otherwise, the values will not be subsitituted, they will only be added.\nIt accepts the following parameters:\n\n- `klass` -> The model on the side `1` of a `1:N` relationship, the owner of the relation,\nin which the new values will be set\n- `attr` -> A string version of the attribute corresponding to the `related_name` value\nin the foreign key field\n- `value` -> A list (or any other iterable), containing new created instances of `related_klass`\n- `related_klass` -> The model on the side `N` of a `1:N` relationship, the one having the foreign\nkey field\n- `**kwargs` -> Keyword arguments used in a filter to determine which objects should be destroyed.\nIt could be really anything, but usually you will want it to be something like `klass=None`, so\nthat all objects that are no part of the relationship anymore can be descarded.\n\nFor instance, a `Movie` may have many `Video`s related to it, like teasers and trailers. In case\nyou want to update a `Movie`, reseting its `Video`s:\n\n```python\n# models.py\n\nclass Movie(models.Model):\n    ...\n\n\nclass Video(models.Model):\n    id = models.UUIDField(primary_key=True, editable=False, default=uuid4)\n    title = models.CharField(max_length=127)\n    url = models.URLField()\n\n    movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name=\"videos\", null=True)\n```\n\n```python\n# serializers.py\n\nfrom dj_drf_utils.helpers import set_and_destroy\n\n\nclass MovieSerializer(serializers.ModelSerializer):\n    ...\n\n    def update(self, instance: Movie, validated_data: dict):\n      ...\n\n      videos_data = validated_data.pop(\"videos\", None)\n      if videos_data:\n          videos = [\n            Video.get_or_create(**video, movie=instance)[0]\n            for video in videos_data\n          ]\n          set_and_destroy(\n              klass=instance,\n              attr=\"videos\",\n              value=videos,\n              related_klass=Video,\n              movie=None,\n          )\n```\n\nIn the example above, we are first getting or creating video instances, in order to reuse the ones\npassed in the body of the request that may already be in our db. Each video can only be related to\none movie, since it doesn't make sense that two movies have the same trailer or teaser. So when\nassigning this new list of videos to a movie, the `set_and_destroy` function safely deletes all\nvideos having their `movie` foreign key equal to `None`.\n\nI highly encorage you to have a quick look at the source code, it's quite a simple concept.\n\n---\n\n### bulk_get_or_create\n\nDespite the name of this function, it does not translate into a single database hit,\nunfortunatelly. But it is still better than a loop executing `Model.objects.get_or_create`\nin every iteration.\n\nThat's because this function **combines filters and the bulk_create method**.\nDjango querysets are lazy, but in this function they are evaluated on every iteration.\nHowever, in the end **only one** `INSERT` query is performed.\n\n---\n\n#### Important!\nDjango's `Model.objects.bulk_create` method returns a list of newly created instances **without ids**\nwhen working with SQLite. Please, make sure to use PostgreSQL to avoid problems.\n\n---\n\nIt expects the following parameters:\n\n- `klass` -> The model whose values will be retrieved or created\n- `values` -> A list of dictionaries having key value pairs demanded by `klass`\n- `only_create` -> A boolean value. Defaults to `False`. In case you don't care about getting\nexisting values, and just wants to create them, then you can set this arguments to `True`. It\nwill result in just one database hit.\n- `kwargs` -> Key value pairs with extra fields you want to use for filtering/creating instances\nof `klass`. It can be useful for foreign key fields\n\nUsage example:\n\n```python\n# serializers.py\n\nfrom dj_drf_utils.helpers import bulk_get_or_create, set_and_destroy\n\n\nclass MovieSerializer(serializers.ModelSerializer):\n    # ...\n\n    def create(self, validated_data: dict) -> Movie:\n        # ...\n\n        videos_data = validated_data.pop(\"videos\")\n\n        # ...\n\n        bulk_get_or_create(Video, videos_data, movie=movie)\n\n        # ...\n\n    def update(self, instance: Movie, validated_data: dict) -> Movie:\n        # ...\n\n        videos = validated_data.pop(\"videos\", None)\n\n        # ...\n\n        if videos:\n            set_and_destroy(\n                klass=instance,\n                attr=\"videos\",\n                value=bulk_get_or_create(Video, videos, movie=instance),\n                related_klass=Video,\n                movie=None,\n            )\n\n        # ...\n```\n\nNote that in the `update` method, we are combining `set_and_destroy` with `bulk_get_or_create`.\nThat's totally a thing.\n\nI highly encourage you to have a look at the source code, so that you can better understand what's\nhappening under the hood. It's not complicated.\n\n\n## mixins.py\n\nThis module provides useful mixins to be used in Django Rest Framework **generic views** and **viewsets**.\n\n### SerializerByMethodMixin\n\nThis mixin overrides the `get_serializer_class` method of generic views. It's\npurpose is to dinamically define which serializer to use, depending on the request\nmethod. For this to be possible, a new class property should be set, it is:\n\n- `method_serializers` -> It should be a dictionary having it's keys with the names\nof http methods and values as the serializer classes corresponding to each method.\nIf the request method does not match any of the dict keys, it will return the value\nof `self.serializer_class`.\n\nBelow is an example:\n\n```python\n# views.py\n\nfrom dj_drf_utils.mixins import SerializerByMethodMixin\n\n\nclass MyBeautifulGenericView(SerializerByMethodMixin, ListCreateAPIView):\n    queryset = MyWonderfulModel.objects.all()\n    serializer_class = MyDefaultSerializer\n    method_serializers = {\n        \"GET\": MySerialzerToUseInGetRequests,\n    }\n```\n\n---\n\n### SerializerByActionMixin\n\nThis mixin overrides the `get_serializer_class` method of viewsets. It's\npurpose is to dinamically define which serializer to use, depending on the viewset\naction. For this to be possible, a new class property should be set, it is:\n\n- `action_serializers` -> It should be a dictionary having it's keys with the names\nof viewset actions and values as the serializer classes corresponding to each action.\nIf the viewset action does not match any of the dict keys, it will return the value\nof `self.serializer_class`.\n\nBelow is an example:\n\n```python\n# views.py\n\nfrom dj_drf_utils.mixins import SerializerByActionMixin\n\n\nclass MyBeautifulViewSet(SerializerByActionMixin, ModelViewSet):\n    queryset = MyWonderfulModel.objects.all()\n    serializer_class = MyDefaultSerializer\n    action_serializers = {\n        \"create\": MySerializerToUseInCreateActions,\n        \"update\": MySerialzerToUseInUpdateActions,\n        \"partial_update\": MySerialzerToUseInPartialUpdateActions,\n    }\n```\n\n---\n\n### SerializerByDetailActionsMixin\n\nThis mixin overrides the `get_serializer_class` method of viewsets. It's\npurpose is to dinamically define which serializer to use, depending on the viewset\naction. If it is a detail action, that is, one of `retrieve`, `update`, `partial_update`\nand `destroy`, then `self.detail_serializer_class` will be returned. Else, the default\n`self.serializer_class` is used. For this to be possible, a new class property should\nbe set, it is:\n\n- `detail_serializer_class` -> It's value should be a serializer class. This property defines\nwhich serializer to use in detail actions.\n\nBelow is an example:\n\n```python\n# views.py\n\nfrom dj_drf_utils.mixins import SerializerByDetailActionsMixin\n\n\nclass MyBeautifulViewSet(SerializerByDetailActionsMixin, ModelViewSet):\n    queryset = MyWonderfulModel.objects.all()\n    serializer_class = MyDefaultSerializer\n    detail_serializer_class = MyDetailSerializer\n```\n\n---\n\n### SerializerBySafeActionsMixin\n\nThis mixin overrides the `get_serializer_class` method of viewsets. It's\npurpose is to dinamically define which serializer to use, depending on the viewset\naction. If it is a _safe action_, then `self.safe_serializer_class` will be returned.\nElse, the default `self.serializer_class` is returned. A safe action is an action\nlisted in the `safe_actions` class property. For this to be possible, a new class\nproperty should be set, it is:\n\n- `safe_serializer_class` -> Its value should be a serializer class. This property defines\nwhich serializer to use in safe actions.\n\nYou can totally customize what is a \"safe action\". For that, you could change the value\nof `self.safe_actions`.\n\n- `safe_actions` -> It should be a `list[str]`, which each item representing a viewset action,\nconsidered safe for that viewset. The default value is `[\"list\", \"retrieve\"]`\n\nBelow is an example:\n\n```python\n# views.py\n\nfrom dj_drf_utils.mixins import SerializerBySafeActionsMixin\n\n\nclass MyBeautifulViewSet(SerializerBySafeActionsMixin, ModelViewSet):\n    queryset = MyWonderfulModel.objects.all()\n    serializer_class = MyDefaultSerializer\n    safe_serializer_class = MySafeSerializer\n```\n\n## managers.py\n\nThis module provides a custom user manager as a shortcut for whoever wants to customize\ndjango's authentication system to use a different field instead of username for login.\nIt can be really anything, like email, phone, cpf, etc.\n\n### CustomUserManager\n\nA custom user manager that inherits from `django.contrib.auth.models.BaseUserManager`.\nIts purpouse in life is mainly to provide an easy and simple way to implement a login\nand register system that expects another field instead of `username`.\n\nBut what if you desired to customize your users in a way that other info is also required\nfor user creation? No problem, this class is highly customizable.\n\nInstead of having to override the `create` and `create_superuser` methods of `BaseUserManager`,\nyou can inherit from `CustomUserManager` and then simply set some class properties at your will.\nThey work as follows:\n\n- `auth_field_name` -> Defaults to `\"email\"`. Defines what is the name of the field that\nshould be used for login (besides password, of course). Note that this field **must**\nexist in your user model, **having a unique constraint**.\n- `user_is_staff` -> Defaults to `False`. Defines the starting staff status of newly\ncreated users\n- `user_start_active` -> Defaults to `True`. Defines if a user account should start in\nactive state. In cases where users have to confirm their account in some way before getting\naccess, you may wish to set this property to `False`\n- `super_is_staff` -> Defaults to `True`. Defines the starting staff status of newly\ncreated superusers\n- `super_start_active` -> Defaults to `True`. Defines if a superuser account should start in\nactive state. Usually you'll want this value to be `True`, but you're totally free to change\nit, depending on your needs.\n- `required_fields` -> Defaults to `[]`. It should be a `list[str]`. This property defines\nwhich fields are required to be provided upon user creation, besides `self.auth_field_name` and\n`password`. The fields `is_staff`, `is_superuser` and `is_active` should also not be present in\nthis list. It is worth noting that **all fields defined here, must also be defined in your user model**.\nOtherwise, a `ValidationError` is raised.\n\nBelow is an example of how you may customize the behaviour of this class:\n\n```python\n# managers.py\n\nfrom dj_drf_utils.managers import CustomUserManager\n\n\nclass MyOwnUserManager(CustomUserManager):\n    user_start_active = False\n    required_fields = [\"first_name\", \"last_name\"]\n```\n\nIn order to implement a login with email feature, for instance, you have to make some minor\nchanges to your user model. Below are some settings that may come in handy for you to define\nin your model:\n\n```python\n# models.py\n\nfrom .managers import MyOwnUserManager\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\n\n\nclass MyUser(AbstractUser):\n    email = models.EmailField(unique=True)\n\n    username = None\n\n    objects = MyOwnUserManager()\n\n    USERNAME_FIELD = objects.auth_field_name\n    REQUIRED_FIELDS = objects.required_fields\n```\n\nThe `email` property is defined as unique, since it's gonna be used for login (as per the `USERNAME_FIELD`\nproperty). The `objects` property may be either the standard `dj_drf_utils.managers.CustomUserManager`\nor your own manager that inherits from it. In the example above, we are using our own user manager,\nwith some minor customizations. `REQUIRED_FIELDS` refer to the fields you are prompted when creating a\nsuperuser (it must not include the value defined for `USERNAME_FIELD` or `\"password\"`). Defining it to\n`objects.required_fields` prevents you from making mistakes and being redundant. Note that in the example\nabove we are droping the `username` column, but that's not necessary if you still want to have a username\nin your user model.\n\n\n## action_patterns.py\n\nViewsets have the advantage of abstracting away the work of defining routes explicitly,\nbut routers have some limits. They can only go to a certain depth in producing urls.\n\nFor instance, let's imagine a simple application, where you have Bands and Albums.\nIn case you wish to list all Albums of a Band, you could make a request to an enpoint\nlike `/bands/<band_id>/albums/`. That's totally possible with routers. But what if you\nwant a detail route for an Album of a Band? A route like `/bands/<band_id>/albums/<album_id>/`\nwould make sense, right? But routers aren't able to go to such an extent. And you could\ntotally imagine bigger urls in real, bigger applications.\n\nSo defining our routes manually gives us a lot more control. Everything comes with a tradeoff\nthough. When manually defining routes for generic views, you can easily assign each view class\nto their routes, using the `as_view` method. But viewsets are different. One viewset class can\nbe assigned to more than one route. So for that to work, you've gotta do something like [this](https://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/#binding-viewsets-to-urls-explicitly).\n\nIn order to simplify things, and abstract away some boiler plate code, this module provides the\nstandard viewset actions mapped to their corresponding http method. Of course, you may have additional\nactions, customized according to your own needs. In this case, you can config them on your own. But\nthe standard ones are all set here.\n\nUsage example:\n\n```python\n# urls.py\n\nfrom django.urls import path\nfrom dj_drf_utils.action_patterns import STANDARD_DETAIL_PATTERN, STANDARD_PATTERN\n\nfrom . import views\n\n\ncinema_view = views.CinemaViewSet.as_view(STANDARD_PATTERN)\ncinema_detail_view = views.CinemaViewSet.as_view(STANDARD_DETAIL_PATTERN)\n\nurlpatterns = [\n    path(\"\", cinema_view),\n    path(\"<cinema_id>/\", cinema_detail_view),\n]\n```\n\nBut routers are still so cool and so simple to use. So a very good alternative is [drf-nested-routers](https://github.com/alanjds/drf-nested-routers).\nIt really makes it easier to deal with all of this. The `drf-nested-routers` library is designed to\nsolve exactly this problem, and even more.\n\n\n## admin.py\n\nThis module provides a `CustomUserAdmin` class. It inherits from `django.contrib.auth.admin.UserAdmin`.\nHave you ever created a custom user model, added it to admin and then realized that your users passwords\nwere being created unhashed? Then you searched the internet and found out that django provides a `UserAdmin`\nclass that does the job. But what if you customized your authentication system, and you're using another\nfield instead of `username`? In this case, it throws an error, saying that there is no `username` field.\n\nIn order to make things easier, this module provides a class that abstracts away all the boring \nconfigurations you would need to do.\n\n### CustomUserAdmin\n\nThis class inherits from `django.contrib.auth.admin.UserAdmin`. It's purpose in life is to abstract\naway some boring configurations you may need, when you're using a custom user model. The advantage is\nto have the same features that Django standard `UserAdmin` class provides, but in a custom user model,\nhaving a field other than `username` used for authentication.\n\nThis class automaticaly figures out what is your user model, as long as it is pointed to by `AUTH_USER_MODEL`\nsetting in `settings.py`. Also, it takes the care of first checking for the fields you set in your user\nmodel before referencing them. But the **password field is mandatory**.\n\nBelow is an usage example:\n\n```python\n# admin.py\n\nfrom dj_drf_utils.admin import CustomUserAdmin\nfrom .models import User\n\nadmin.site.register(User, CustomUserAdmin)\n```\n\nIn case you want to customize some kind of behaviour, you totally can, but you will have to overwrite the\nproperties entirely. For instance, if you need to change the columns of `list_display`, you could do something\nlike this:\n\n```python\n\n# admin.py\n\nfrom dj_drf_utils.admin import CustomUserAdmin\nfrom .models import User\n\nclass MyOwnUserAdmin(CustomUserAdmin):\n    list_display = ['id', 'email', 'first_name', 'last_name', 'birth_date', 'is_staff', 'is_superuser']\n\nadmin.site.register(User, MyOwnUserAdmin)\n```\n\nNot so bad.\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Useful functions and classes for Django and Django Rest Framework",
    "version": "1.2.0",
    "split_keywords": [
        "django",
        "utils",
        "serializers",
        "generic",
        "views",
        "viewsets",
        "mixins",
        "email",
        "login",
        "model",
        "manager",
        "custom",
        "action",
        "shortcut",
        "error",
        "simple",
        "rest",
        "framework",
        "dj",
        "drf",
        "admin",
        "hash",
        "password",
        "user"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "715d692f1f00350b426a6780f98067cd",
                "sha256": "d18d2ae072b455d005dd6126b4f90b1c7724c168089ed6b150cbab934c8736e2"
            },
            "downloads": -1,
            "filename": "dj_drf_utils-1.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "715d692f1f00350b426a6780f98067cd",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 18856,
            "upload_time": "2022-09-18T22:24:17",
            "upload_time_iso_8601": "2022-09-18T22:24:17.176186Z",
            "url": "https://files.pythonhosted.org/packages/74/e6/c171562eb3f23a9347e337bb416e2053f945660a3cf78ba9e91ab60c5f3c/dj_drf_utils-1.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-09-18 22:24:17",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "cayo-rodrigues",
    "github_project": "django-utils",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "asgiref",
            "specs": [
                [
                    "==",
                    "3.5.2"
                ]
            ]
        },
        {
            "name": "bleach",
            "specs": [
                [
                    "==",
                    "5.0.1"
                ]
            ]
        },
        {
            "name": "certifi",
            "specs": [
                [
                    "==",
                    "2022.6.15"
                ]
            ]
        },
        {
            "name": "cffi",
            "specs": [
                [
                    "==",
                    "1.15.1"
                ]
            ]
        },
        {
            "name": "charset-normalizer",
            "specs": [
                [
                    "==",
                    "2.1.0"
                ]
            ]
        },
        {
            "name": "commonmark",
            "specs": [
                [
                    "==",
                    "0.9.1"
                ]
            ]
        },
        {
            "name": "cryptography",
            "specs": [
                [
                    "==",
                    "37.0.4"
                ]
            ]
        },
        {
            "name": "Django",
            "specs": [
                [
                    "==",
                    "4.1"
                ]
            ]
        },
        {
            "name": "djangorestframework",
            "specs": [
                [
                    "==",
                    "3.13.1"
                ]
            ]
        },
        {
            "name": "docutils",
            "specs": [
                [
                    "==",
                    "0.19"
                ]
            ]
        },
        {
            "name": "idna",
            "specs": [
                [
                    "==",
                    "3.3"
                ]
            ]
        },
        {
            "name": "importlib-metadata",
            "specs": [
                [
                    "==",
                    "4.12.0"
                ]
            ]
        },
        {
            "name": "jeepney",
            "specs": [
                [
                    "==",
                    "0.8.0"
                ]
            ]
        },
        {
            "name": "keyring",
            "specs": [
                [
                    "==",
                    "23.8.2"
                ]
            ]
        },
        {
            "name": "pkginfo",
            "specs": [
                [
                    "==",
                    "1.8.3"
                ]
            ]
        },
        {
            "name": "pycparser",
            "specs": [
                [
                    "==",
                    "2.21"
                ]
            ]
        },
        {
            "name": "Pygments",
            "specs": [
                [
                    "==",
                    "2.13.0"
                ]
            ]
        },
        {
            "name": "pytz",
            "specs": [
                [
                    "==",
                    "2022.2.1"
                ]
            ]
        },
        {
            "name": "readme-renderer",
            "specs": [
                [
                    "==",
                    "36.0"
                ]
            ]
        },
        {
            "name": "requests",
            "specs": [
                [
                    "==",
                    "2.28.1"
                ]
            ]
        },
        {
            "name": "requests-toolbelt",
            "specs": [
                [
                    "==",
                    "0.9.1"
                ]
            ]
        },
        {
            "name": "rfc3986",
            "specs": [
                [
                    "==",
                    "2.0.0"
                ]
            ]
        },
        {
            "name": "rich",
            "specs": [
                [
                    "==",
                    "12.5.1"
                ]
            ]
        },
        {
            "name": "SecretStorage",
            "specs": [
                [
                    "==",
                    "3.3.3"
                ]
            ]
        },
        {
            "name": "six",
            "specs": [
                [
                    "==",
                    "1.16.0"
                ]
            ]
        },
        {
            "name": "sqlparse",
            "specs": [
                [
                    "==",
                    "0.4.2"
                ]
            ]
        },
        {
            "name": "twine",
            "specs": [
                [
                    "==",
                    "4.0.1"
                ]
            ]
        },
        {
            "name": "urllib3",
            "specs": [
                [
                    "==",
                    "1.26.11"
                ]
            ]
        },
        {
            "name": "webencodings",
            "specs": [
                [
                    "==",
                    "0.5.1"
                ]
            ]
        },
        {
            "name": "zipp",
            "specs": [
                [
                    "==",
                    "3.8.1"
                ]
            ]
        }
    ],
    "lcname": "dj-drf-utils"
}
        
Elapsed time: 0.47910s