air-drf-relation


Nameair-drf-relation JSON
Version 0.6.1 PyPI version JSON
download
home_pagehttps://github.com/bubaley/air-drf-relation
SummaryImproved interaction with DRF relations.
upload_time2024-04-26 07:45:58
maintainerNone
docs_urlNone
authorbubaley
requires_pythonNone
licenseMIT
keywords django rest relation nested pk primary object
VCS
bugtrack_url
requirements asgiref bleach build certifi chardet colorama dacite Django django-environ django-filter djangorestframework djangorestframework-dataclasses docutils idna importlib-metadata keyring packaging pep517 Pillow pkginfo Pygments pyparsing pytz readme-renderer requests requests-toolbelt rfc3986 six sqlparse toml tqdm twine urllib3 webencodings zipp
Travis-CI No Travis.
coveralls test coverage No coveralls.
            **AIR-DRF-RELATION**

# Table of Contents

1. [Instalation](#instalation)
2. [About](#about)
3. [AirRelatedField](#airrelatedfield)
    1. [pk_only](#pk_only)
    2. [hidden](#hidden)
4. [AirModelSerializer](#airmodelserializer)
    1. [user](#user)
    2. [extra_kwargs](#extra_kwargs)
    3. [hidden_fields](#hidden_fields)
    4. [Kwargs by actions](#kwargs-by-actions)
        1. [action_read_only_fields](#action_read_only_fields)
        2. [action_hidden_fields](#action_hidden_fields)
        3. [action_extra_kwargs](#action_extra_kwargs)
    4. [Priority extra_kwargs](#priority-extra_kwargs)
    5. [Filter nested querysets](#filter-nested-querysets)

# Instalation

`$ pip install air-drf-relation`

# About

`air-drf-relation` adds flexibility and convenience in working with ModelSerializer.

# AirRelatedField

Used to extend the functionality of the `PrimaryKeyRelatedField`

```python
class BookSerializer(ModelSerializer):
    # author = PrimaryKeyRelatedField(queryset=Author.objects) - default usage
    author = AirRelatedField(AuthorSerializer)
    city = AirRelatedField(CitySerializer)

    class Meta:
        model = Book
        fields = ('uuid', 'name', 'author', 'city')
```

`AirRelatedField` allows you to get not only pk but also an object with pk, which will be searched.
```json
{
    "name": "demo",
    "author": { 
        "id": 1
    },
    "city": 1
}
```
## pk_only
Automatically AirRelatedField returns a serialized object. If you only want to use pk, you must specify the `pk_only` key.

```python
author = AirRelatedField(AuthorSerializer, pk_only=True)
```

## hidden
Hidden fields are not used for serialization and validation. The data will be returned without fields. Usually used together in `AirModelSerializer`

```python
author = AirRelatedField(AuthorSerializer, hidden=True)
```

## Important
You cannot use `hidden` and `pk_only` in ModelSerializer and with extra_kwargs

# AirModelSerializer

Used to extend the functionality of the `ModelSerializer`

```python
class BookSerializer(AirModelSerializer): # full example
    author = AirRelatedField(AuthorSerializer)
    city = AirRelatedField(AuthorSerializer)

    class Meta:
        model = Book
        fields = ('uuid', 'name', 'author', 'city')
        hidden_fields = ()
        read_only_fields = () # default read_only_fields
        extra_kwargs = {} # default extra_kwargs with support custom keys
        action_read_only_fields = {
            'create': {},
            '_': {} # used for other actions
        },
        action_hidden_fields = {
            'create': (),
            '_': ()
        }
        action_extra_kwargs = {
            'list': {},
            '_': {}
        }
        nested_save_fields = ()
```

## user
User is automatically put from the `request` if available. You can also set the user manually.

```python
class DemoSerializer(AirModelSerializer):
    class Meta:
        fields = ('id', 'name')
    
    validate_name(self, value):
        if not self.user:
            return None
        return value
```
Manually set user.
```python
serializer = DemoSerializer(data={'name': 'demo'}, user=request.user)
```

## extra_kwargs
Extends the standard work with `extra_kwargs` by adding work with additional attributes. You can also transfer `extra_kwargs` manually.

```python
class BookSerializer(AirModelSerializer):
    author = AirRelatedField(AuthorSerializer)
    
    class Meta:
        fields = ('id', 'name', 'author')
        extra_kwargs = {
            'author': {'pk_only': True},
            'name': {'hidden': True}
        }
```
## hidden_fields
Hides fields for validation and seralization.
```python
class BookSerializer(AirModelSerializer):
    class Meta:
        fields = ('id', 'name', 'author')
        hidden_fields = ('name', 'author')
```
## Kwargs by actions
Kwargs by actions is used only when the event. You can pass acions separated by `,`.
For events that don't match, you can use `_` key. It is used if action **is passed**.
Action is set automatically from the ViewSet, or it can be passed manually.

```python
class DemoViewSet(ModelViewSet):
    queryset = Demo.objects.all()
    serializer_class = DemoSerializer
    
    def perform_create(serializer, request):
        action = serializer.action # action is 'create'
        serializer.save()
    
    @action(methods=['POST'], detail=False)
    def demo_action(self, request):
        serializer = self.get_serializer_class()
        action = serializer.action # action is 'demo_action'
```

Manually set action.
```python
serializer = DemoSerializer(data={'name': 'demo'}, action='custom_action')
action = serializer.action # action is 'custom_action'
```

### action_read_only_fields
Sets `read_only_fields` by action in serializer.

```python
class BookSerializer(AirModelSerializer):
    class Meta:
        fields = ('id', 'name', 'author')
        action_read_only_fields = {
            'create,update': ('name', 'author')
        }
```

### action_hidden_fields
Sets `hidden_fields` by action in serializer.

```python
class BookSerializer(AirModelSerializer):
    class Meta:
        fields = ('id', 'name', 'author')
        action_hidden_fields = {
            'custom_action': ('author', ),
            '_': ('id', )
        }
```

### action_extra_kwargs
Expand `extra_kwargs` by action in serializer.

```python
class BookSerializer(AirModelSerializer):
    author = AirRelatedField(AuthorSerializer, pk_only=True, null=True)
    
    class Meta:
        fields = ('id', 'name', 'author')
        action_extra_kwargs = {
            'create,custom_update': {
                'author': {'pk_only': False, 'null'=True}
            }
        }
```

## Priority extra_kwargs
Below are the priorities of the extra_kwargs extension in ascending order
1. extra_kwargs `in Meta`
2. hidden_fields
3. action_hidden_fields
4. action_read_only_fields
5. action_extra_kwargs
6. extra_kwargs `manually transmitted`

## Filter nested querysets
AirModelSerializer allows you to filter the queryset by nested fields.
```python
class BookSerializer(AirModelSerializer):
    city = AirRelatedField(CitySerializer, queryset_function_name='custom_filter')

    def queryset_author(self, queryset):
        return queryset.filter(active=True, created_by=self.user)

    def filter_city_by_active(self, queryset):
        return queryset.filter(active=True)

    class Meta:
        model = Book
        fields = ('uuid', 'name', 'author', 'city')
```
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/bubaley/air-drf-relation",
    "name": "air-drf-relation",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "django rest relation nested pk primary object",
    "author": "bubaley",
    "author_email": "bubaley.fu@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/e1/9e/bdebc0afe3f6fc67bdf1b2eaf1c1a8bdc45ab1569abf9aa24c6ac4072068/air_drf_relation-0.6.1.tar.gz",
    "platform": null,
    "description": "**AIR-DRF-RELATION**\n\n# Table of Contents\n\n1. [Instalation](#instalation)\n2. [About](#about)\n3. [AirRelatedField](#airrelatedfield)\n    1. [pk_only](#pk_only)\n    2. [hidden](#hidden)\n4. [AirModelSerializer](#airmodelserializer)\n    1. [user](#user)\n    2. [extra_kwargs](#extra_kwargs)\n    3. [hidden_fields](#hidden_fields)\n    4. [Kwargs by actions](#kwargs-by-actions)\n        1. [action_read_only_fields](#action_read_only_fields)\n        2. [action_hidden_fields](#action_hidden_fields)\n        3. [action_extra_kwargs](#action_extra_kwargs)\n    4. [Priority extra_kwargs](#priority-extra_kwargs)\n    5. [Filter nested querysets](#filter-nested-querysets)\n\n# Instalation\n\n`$ pip install air-drf-relation`\n\n# About\n\n`air-drf-relation` adds flexibility and convenience in working with ModelSerializer.\n\n# AirRelatedField\n\nUsed to extend the functionality of the `PrimaryKeyRelatedField`\n\n```python\nclass BookSerializer(ModelSerializer):\n    # author = PrimaryKeyRelatedField(queryset=Author.objects) - default usage\n    author = AirRelatedField(AuthorSerializer)\n    city = AirRelatedField(CitySerializer)\n\n    class Meta:\n        model = Book\n        fields = ('uuid', 'name', 'author', 'city')\n```\n\n`AirRelatedField` allows you to get not only pk but also an object with pk, which will be searched.\n```json\n{\n    \"name\": \"demo\",\n    \"author\": { \n        \"id\": 1\n    },\n    \"city\": 1\n}\n```\n## pk_only\nAutomatically AirRelatedField returns a serialized object. If you only want to use pk, you must specify the `pk_only` key.\n\n```python\nauthor = AirRelatedField(AuthorSerializer, pk_only=True)\n```\n\n## hidden\nHidden fields are not used for serialization and validation. The data will be returned without fields. Usually used together in `AirModelSerializer`\n\n```python\nauthor = AirRelatedField(AuthorSerializer, hidden=True)\n```\n\n## Important\nYou cannot use `hidden` and `pk_only` in ModelSerializer and with extra_kwargs\n\n# AirModelSerializer\n\nUsed to extend the functionality of the `ModelSerializer`\n\n```python\nclass BookSerializer(AirModelSerializer): # full example\n    author = AirRelatedField(AuthorSerializer)\n    city = AirRelatedField(AuthorSerializer)\n\n    class Meta:\n        model = Book\n        fields = ('uuid', 'name', 'author', 'city')\n        hidden_fields = ()\n        read_only_fields = () # default read_only_fields\n        extra_kwargs = {} # default extra_kwargs with support custom keys\n        action_read_only_fields = {\n            'create': {},\n            '_': {} # used for other actions\n        },\n        action_hidden_fields = {\n            'create': (),\n            '_': ()\n        }\n        action_extra_kwargs = {\n            'list': {},\n            '_': {}\n        }\n        nested_save_fields = ()\n```\n\n## user\nUser is automatically put from the `request` if available. You can also set the user manually.\n\n```python\nclass DemoSerializer(AirModelSerializer):\n    class Meta:\n        fields = ('id', 'name')\n    \n    validate_name(self, value):\n        if not self.user:\n            return None\n        return value\n```\nManually set user.\n```python\nserializer = DemoSerializer(data={'name': 'demo'}, user=request.user)\n```\n\n## extra_kwargs\nExtends the standard work with `extra_kwargs` by adding work with additional attributes. You can also transfer `extra_kwargs` manually.\n\n```python\nclass BookSerializer(AirModelSerializer):\n    author = AirRelatedField(AuthorSerializer)\n    \n    class Meta:\n        fields = ('id', 'name', 'author')\n        extra_kwargs = {\n            'author': {'pk_only': True},\n            'name': {'hidden': True}\n        }\n```\n## hidden_fields\nHides fields for validation and seralization.\n```python\nclass BookSerializer(AirModelSerializer):\n    class Meta:\n        fields = ('id', 'name', 'author')\n        hidden_fields = ('name', 'author')\n```\n## Kwargs by actions\nKwargs by actions is used only when the event. You can pass acions separated by `,`.\nFor events that don't match, you can use `_` key. It is used if action **is passed**.\nAction is set automatically from the ViewSet, or it can be passed manually.\n\n```python\nclass DemoViewSet(ModelViewSet):\n    queryset = Demo.objects.all()\n    serializer_class = DemoSerializer\n    \n    def perform_create(serializer, request):\n        action = serializer.action # action is 'create'\n        serializer.save()\n    \n    @action(methods=['POST'], detail=False)\n    def demo_action(self, request):\n        serializer = self.get_serializer_class()\n        action = serializer.action # action is 'demo_action'\n```\n\nManually set action.\n```python\nserializer = DemoSerializer(data={'name': 'demo'}, action='custom_action')\naction = serializer.action # action is 'custom_action'\n```\n\n### action_read_only_fields\nSets `read_only_fields` by action in serializer.\n\n```python\nclass BookSerializer(AirModelSerializer):\n    class Meta:\n        fields = ('id', 'name', 'author')\n        action_read_only_fields = {\n            'create,update': ('name', 'author')\n        }\n```\n\n### action_hidden_fields\nSets `hidden_fields` by action in serializer.\n\n```python\nclass BookSerializer(AirModelSerializer):\n    class Meta:\n        fields = ('id', 'name', 'author')\n        action_hidden_fields = {\n            'custom_action': ('author', ),\n            '_': ('id', )\n        }\n```\n\n### action_extra_kwargs\nExpand `extra_kwargs` by action in serializer.\n\n```python\nclass BookSerializer(AirModelSerializer):\n    author = AirRelatedField(AuthorSerializer, pk_only=True, null=True)\n    \n    class Meta:\n        fields = ('id', 'name', 'author')\n        action_extra_kwargs = {\n            'create,custom_update': {\n                'author': {'pk_only': False, 'null'=True}\n            }\n        }\n```\n\n## Priority extra_kwargs\nBelow are the priorities of the extra_kwargs extension in ascending order\n1. extra_kwargs `in Meta`\n2. hidden_fields\n3. action_hidden_fields\n4. action_read_only_fields\n5. action_extra_kwargs\n6. extra_kwargs `manually transmitted`\n\n## Filter nested querysets\nAirModelSerializer allows you to filter the queryset by nested fields.\n```python\nclass BookSerializer(AirModelSerializer):\n    city = AirRelatedField(CitySerializer, queryset_function_name='custom_filter')\n\n    def queryset_author(self, queryset):\n        return queryset.filter(active=True, created_by=self.user)\n\n    def filter_city_by_active(self, queryset):\n        return queryset.filter(active=True)\n\n    class Meta:\n        model = Book\n        fields = ('uuid', 'name', 'author', 'city')\n```",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Improved interaction with DRF relations.",
    "version": "0.6.1",
    "project_urls": {
        "Homepage": "https://github.com/bubaley/air-drf-relation"
    },
    "split_keywords": [
        "django",
        "rest",
        "relation",
        "nested",
        "pk",
        "primary",
        "object"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e19ebdebc0afe3f6fc67bdf1b2eaf1c1a8bdc45ab1569abf9aa24c6ac4072068",
                "md5": "1561534030b631d204e0adc9fea32b72",
                "sha256": "67279d45e29e0419e538ef61ec4ee94c796b79b82062fa78d8850a5f88497e17"
            },
            "downloads": -1,
            "filename": "air_drf_relation-0.6.1.tar.gz",
            "has_sig": false,
            "md5_digest": "1561534030b631d204e0adc9fea32b72",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 33821,
            "upload_time": "2024-04-26T07:45:58",
            "upload_time_iso_8601": "2024-04-26T07:45:58.007601Z",
            "url": "https://files.pythonhosted.org/packages/e1/9e/bdebc0afe3f6fc67bdf1b2eaf1c1a8bdc45ab1569abf9aa24c6ac4072068/air_drf_relation-0.6.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-26 07:45:58",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "bubaley",
    "github_project": "air-drf-relation",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "asgiref",
            "specs": [
                [
                    "==",
                    "3.3.4"
                ]
            ]
        },
        {
            "name": "bleach",
            "specs": [
                [
                    "==",
                    "3.3.0"
                ]
            ]
        },
        {
            "name": "build",
            "specs": [
                [
                    "==",
                    "0.5.1"
                ]
            ]
        },
        {
            "name": "certifi",
            "specs": [
                [
                    "==",
                    "2021.5.30"
                ]
            ]
        },
        {
            "name": "chardet",
            "specs": [
                [
                    "==",
                    "4.0.0"
                ]
            ]
        },
        {
            "name": "colorama",
            "specs": [
                [
                    "==",
                    "0.4.4"
                ]
            ]
        },
        {
            "name": "dacite",
            "specs": [
                [
                    "==",
                    "1.8.1"
                ]
            ]
        },
        {
            "name": "Django",
            "specs": [
                [
                    "==",
                    "4.2.2"
                ]
            ]
        },
        {
            "name": "django-environ",
            "specs": [
                [
                    "==",
                    "0.4.5"
                ]
            ]
        },
        {
            "name": "django-filter",
            "specs": [
                [
                    "==",
                    "21.1"
                ]
            ]
        },
        {
            "name": "djangorestframework",
            "specs": [
                [
                    "==",
                    "3.14.0"
                ]
            ]
        },
        {
            "name": "djangorestframework-dataclasses",
            "specs": [
                [
                    "==",
                    "1.2.0"
                ]
            ]
        },
        {
            "name": "docutils",
            "specs": [
                [
                    "==",
                    "0.17.1"
                ]
            ]
        },
        {
            "name": "idna",
            "specs": [
                [
                    "==",
                    "2.10"
                ]
            ]
        },
        {
            "name": "importlib-metadata",
            "specs": [
                [
                    "==",
                    "4.6.0"
                ]
            ]
        },
        {
            "name": "keyring",
            "specs": [
                [
                    "==",
                    "23.0.1"
                ]
            ]
        },
        {
            "name": "packaging",
            "specs": [
                [
                    "==",
                    "20.9"
                ]
            ]
        },
        {
            "name": "pep517",
            "specs": [
                [
                    "==",
                    "0.10.0"
                ]
            ]
        },
        {
            "name": "Pillow",
            "specs": [
                [
                    "==",
                    "8.3.1"
                ]
            ]
        },
        {
            "name": "pkginfo",
            "specs": [
                [
                    "==",
                    "1.7.0"
                ]
            ]
        },
        {
            "name": "Pygments",
            "specs": [
                [
                    "==",
                    "2.9.0"
                ]
            ]
        },
        {
            "name": "pyparsing",
            "specs": [
                [
                    "==",
                    "2.4.7"
                ]
            ]
        },
        {
            "name": "pytz",
            "specs": [
                [
                    "==",
                    "2021.1"
                ]
            ]
        },
        {
            "name": "readme-renderer",
            "specs": [
                [
                    "==",
                    "29.0"
                ]
            ]
        },
        {
            "name": "requests",
            "specs": [
                [
                    "==",
                    "2.25.1"
                ]
            ]
        },
        {
            "name": "requests-toolbelt",
            "specs": [
                [
                    "==",
                    "0.9.1"
                ]
            ]
        },
        {
            "name": "rfc3986",
            "specs": [
                [
                    "==",
                    "1.5.0"
                ]
            ]
        },
        {
            "name": "six",
            "specs": [
                [
                    "==",
                    "1.16.0"
                ]
            ]
        },
        {
            "name": "sqlparse",
            "specs": [
                [
                    "==",
                    "0.4.1"
                ]
            ]
        },
        {
            "name": "toml",
            "specs": [
                [
                    "==",
                    "0.10.2"
                ]
            ]
        },
        {
            "name": "tqdm",
            "specs": [
                [
                    "==",
                    "4.61.1"
                ]
            ]
        },
        {
            "name": "twine",
            "specs": [
                [
                    "==",
                    "3.4.1"
                ]
            ]
        },
        {
            "name": "urllib3",
            "specs": [
                [
                    "==",
                    "1.26.6"
                ]
            ]
        },
        {
            "name": "webencodings",
            "specs": [
                [
                    "==",
                    "0.5.1"
                ]
            ]
        },
        {
            "name": "zipp",
            "specs": [
                [
                    "==",
                    "3.4.1"
                ]
            ]
        }
    ],
    "lcname": "air-drf-relation"
}
        
Elapsed time: 0.21367s