Reputation: 107
I am trying to achieve my event model with tags object nested with it. But tags have only name field, I need both id, name and slug as well.
here is my Model looks like
model.py
class Event(models.Model):
title = models.CharField(max_length=151, db_index=True)
description = models.TextField(blank=True, null=True)
tags = TaggableManager()
serializers.py
class EventSerializer(serializers.ModelSerializer):
slug = serializers.SerializerMethodField()
tags = TagListSerializerField()
the Result I am having:
{
"id": 52,
"slug": "52-aperiam-amet",
"tags": [
"hello",
"world"
],
"title": "Aperiam amet",
"description": "Quibusdam ipsum sun Quibusdam ipsum sun Quibusdam ipsum sun ",
},
but expected tags nest should look like
"tags": [
{
id:"1",
slug:'1-hello',
name:"hello"
},
{
id:"2",
slug:'2-world',
name:"world"
},
],
Upvotes: 1
Views: 67
Reputation: 476493
You can work with a TagSerializer
:
from taggit.models import Tag
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('id', 'name', 'slug')
and then work with:
class EventSerializer(serializers.ModelSerializer):
slug = serializers.SerializerMethodField()
tags = TagSerializer(many=True)
That being said, essentially Taggit
aims to hide the tag model and expose it as just strings, this is likely the main task django-taggit
aims to achieve, and likely is better since exposing the primary key makes it more complicated.
Upvotes: 1