Django REST Framework lookup_field to ReadOnlyField with source

Multi tool use
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I have a 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]
And 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)
And serializer
returns hash
instead of 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"
But, if I want to get an object by hash
, not an id
, I don’t get a result.
How can I get an object by hash
?
python django django-rest-framework
add a comment |
I have a 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]
And 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)
And serializer
returns hash
instead of 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"
But, if I want to get an object by hash
, not an id
, I don’t get a result.
How can I get an object by hash
?
python django django-rest-framework
Is yourhash
a DB field or a property?
– JPG
Jan 4 at 4:09
@JPG,property
– Narnik Gamarnik
Jan 10 at 22:35
add a comment |
I have a 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]
And 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)
And serializer
returns hash
instead of 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"
But, if I want to get an object by hash
, not an id
, I don’t get a result.
How can I get an object by hash
?
python django django-rest-framework
I have a 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]
And 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)
And serializer
returns hash
instead of 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"
But, if I want to get an object by hash
, not an id
, I don’t get a result.
How can I get an object by hash
?
python django django-rest-framework
python django django-rest-framework
asked Jan 3 at 21:42


Narnik GamarnikNarnik Gamarnik
321214
321214
Is yourhash
a DB field or a property?
– JPG
Jan 4 at 4:09
@JPG,property
– Narnik Gamarnik
Jan 10 at 22:35
add a comment |
Is yourhash
a DB field or a property?
– JPG
Jan 4 at 4:09
@JPG,property
– Narnik Gamarnik
Jan 10 at 22:35
Is your
hash
a DB field or a property?– JPG
Jan 4 at 4:09
Is your
hash
a DB field or a property?– JPG
Jan 4 at 4:09
@JPG,
property
– Narnik Gamarnik
Jan 10 at 22:35
@JPG,
property
– Narnik Gamarnik
Jan 10 at 22:35
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54030209%2fdjango-rest-framework-lookup-field-to-readonlyfield-with-source%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54030209%2fdjango-rest-framework-lookup-field-to-readonlyfield-with-source%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
AY4YnII3ySlH6RnEMkm ZFT,dRcdg,3wNdBaEMNuLquj,WKZi,QHya
Is your
hash
a DB field or a property?– JPG
Jan 4 at 4:09
@JPG,
property
– Narnik Gamarnik
Jan 10 at 22:35