-
Notifications
You must be signed in to change notification settings - Fork 300
-
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
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 2 replies
-
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.
Beta Was this translation helpful? Give feedback.
All reactions
-
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
Beta Was this translation helpful? Give feedback.
All reactions
-
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.
Beta Was this translation helpful? Give feedback.