Skip to content

Commit

Permalink
Add ModelFromUUIDField
Browse files Browse the repository at this point in the history
  • Loading branch information
Maxim Belkin committed Oct 4, 2020
1 parent 0ed68ea commit 686605e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
17 changes: 15 additions & 2 deletions restdoctor/rest_framework/fields.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
from __future__ import annotations
import datetime
from typing import Optional, Union, Any
from typing import Optional, Union, Any, TYPE_CHECKING

from django.db import models
from rest_framework import ISO_8601
from rest_framework.fields import DateTimeField as BaseDateTimeField
from rest_framework.fields import DateTimeField as BaseDateTimeField, UUIDField
from rest_framework.relations import HyperlinkedIdentityField as BaseHyperlinkedIdentityField
from rest_framework.request import Request
from rest_framework.settings import api_settings

from restdoctor.rest_framework.reverse import preserve_resource_params

if TYPE_CHECKING:
import uuid
from django.db.models import Model, QuerySet


class DateTimeField(BaseDateTimeField):
def to_representation(
Expand All @@ -36,3 +40,12 @@ class HyperlinkedIdentityField(BaseHyperlinkedIdentityField):
def get_url(self, obj: models.Model, view_name: str, request: Request, *args: Any, **kwargs: Any) -> str:
url = super().get_url(obj, view_name, request, *args, **kwargs)
return preserve_resource_params(url, request)


class ModelFromUUIDField(UUIDField):
def __init__(self, queryset: QuerySet, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.queryset = queryset

def to_representation(self, uuid: uuid.UUID) -> Optional[Model]:
return self.queryset.filter(uuid=uuid).first()
12 changes: 11 additions & 1 deletion tests/test_unit/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import pytz
from django.utils.timezone import make_aware

from restdoctor.rest_framework.fields import DateTimeField
from restdoctor.rest_framework.fields import DateTimeField, ModelFromUUIDField
from tests.stubs.models import MyModel


@pytest.mark.parametrize(
Expand All @@ -21,3 +22,12 @@ def test_datetime_field_to_representation(
datetime_obj, expected_string_representation,
):
assert DateTimeField().to_representation(datetime_obj) == expected_string_representation


@pytest.mark.django_db
def test_model_from_uuid_field_to_representation(
my_model,
):
queryset = MyModel.objects.all()

assert ModelFromUUIDField(queryset=queryset).to_representation(my_model.uuid) == my_model

0 comments on commit 686605e

Please sign in to comment.