带有源的Django REST Framework lookup_field到ReadOnlyField

时间:2019-01-03 21:42:46

标签: python django django-rest-framework

我有一个class

from django.contrib.contenttypes.models import ContentType

import basehash


class Hasher(object):

    base62 = basehash.base62()

    @classmethod
    def from_model(cls, obj, klass=None):
        if obj.pk is None:
            return None
        return cls.make_hash(obj.pk, klass if klass is not None else obj)

    @classmethod
    def make_hash(cls, object_pk, klass):
        content_type = ContentType.objects.get_for_model(
            klass, for_concrete_model=False
        )
        return cls.base62.hash(
            "%(contenttype_pk)03d%(object_pk)06d"
            % {"contenttype_pk": content_type.pk, "object_pk": object_pk}
        )

    @classmethod
    def parse_hash(cls, obj_hash):
        unhashed = "%09d" % cls.base62.unhash(obj_hash)
        contenttype_pk = int(unhashed[:-6])
        object_pk = int(unhashed[-6:])
        return contenttype_pk, object_pk

    @classmethod
    def to_object_pk(cls, obj_hash):
        return cls.parse_hash(obj_hash)[1]

还有models

class HashableModel(Model):
    """Provide a hash property for models."""

    class Meta:
        abstract = True

    @property
    def hash(self):
        return Hasher.from_model(self)


class Contest(HashableModel, Base):  # type: ignore

    event = ForeignKey("events.Event", on_delete=CASCADE, related_name="contests")
    owner = ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="contests"
    )

    members = ManyToManyField(settings.AUTH_USER_MODEL, blank=True)

然后serializer返回hash而不是id

class ContestSerializer(serializers.ModelSerializer):

    """Serialize a `contests.Contest` instance."""

    id = serializers.ReadOnlyField(source="hash")
    event = EventSerializer()
    owner = UserSerializer()
    members = UserSerializer(many=True)

    class Meta:
        model = Contest
        lookup_field = "id"
        exclude = ("is_removed",)


class ContestViewSet(
    mixins.CreateModelMixin,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    viewsets.GenericViewSet,
):
    """
    A simple ViewSet for creating and viewing contests.
    """

    queryset = Contest.objects.all()
    serializer_class = ContestSerializer
    lookup_field = "id"

但是,如果我想通过hash而不是id来获取对象,则不会得到结果。

enter image description here

如何通过hash获取对象?

0 个答案:

没有答案