Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Display UUID or slug instead of the ID #1188

Unanswered
jaimeres asked this question in Q&A
Discussion options

Hi,
Is it possible to hide the numerical ID and instead display a slug or UUID, similar to how DRF uses lookup_field?

python


class AssetViewSet(ModelViewSet):
 serializer_class = AssetSerializer
 lookup_field = 'slug'
class Asset(models.Model):
 slug = models.SlugField(max_length=36, unique=True, editable=False, default=uuid.uuid4)
 name = models.CharField(max_length=50)

Desired outcome

{
 "data": {
 "type": "asset",
 "id": "81866c4d-35a6-4b33-9b79-3b5e90e2a3db",
 "attributes": {
 "name": "Example"
 }
 }
}

Try as indicated in the documentation.

**Overwriting the resource object’s id

Per default the primary key property pk on the instance is used as the resource identifier.

It is possible to overwrite the resource id by defining an id field on the serializer like:**

class UserSerializer(serializers.ModelSerializer):
 id = serializers.CharField(source='email')
 name = serializers.CharField()
 class Meta:
 model = User
You must be logged in to vote

Replies: 1 comment 2 replies

Comment options

This is a fairly recent feature, so you need to make sure that you have at least version 6.1.0 installed.

Then in your case, something like the following should work:

class AssetViewSet(ModelViewSet):
 serializer_class = AssetSerializer
 lookup_field = 'slug'
class Asset(models.Model):
 id = models.SlugField(max_length=36, unique=True, editable=False, source='slug')
 name = models.CharField(max_length=50)

Have a try and see how it works.

You must be logged in to vote
2 replies
Comment options

Magnificent, thank you @sliverc
I updated to version 6.1.0 and it worked. I just have a question about your example; the actual ID would be of type slug, and I want it to be an auto-incremental integer, where the API consumer visualizes the slug as the ID. That's why I only use it in the serializer and the view

Comment options

Not 100% sure what you are trying to accomplish. However, Django REST framework JSON:API simply expects a serializer field with the name id. This field can be of any field type (does not have to be a slug) whatever is supported by Django REST framework. Just note that DJA will convert it to a string, as that is a JSON:API requirement for id.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants

AltStyle によって変換されたページ (->オリジナル) /