1

I want many to many fields to be displayed in module serializer instead of id, these are my serializers

class TrainerSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id', ]


class ModuleSerializer(serializers.ModelSerializer):

    trainer = serializers.CharField(source='trainer.username')

    class Meta:
        model = Module
        fields = ['id', 'title', 'duration', 'trainer', 

'publish_choice']

class Trainer(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return str(self.user)

    class Meta:
        ordering = ['pk']


class Module(models.Model):
    title = models.CharField(max_length=80, unique=True)
    duration = models.IntegerField(verbose_name='Duration in Days/ Weeks', blank=True, null=True)
    trainer = models.ManyToManyField(Trainer, blank=True)
    detail = models.TextField(verbose_name='Program Details', blank=True, null=True)
    notify = models.BooleanField(default=False)
    publish_choice = models.CharField(verbose_name='Publish/ Draft',
                                      max_length=80, choices=PUBLISH_CHOICES, default='publish')

and this is the error message

Got AttributeError when attempting to get a value for field trainer on serializer ModuleSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Module instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'username'.

0

2 Answers 2

1

We have a depth parameter in the serializer MetaClass. we can make use of it like below. depth=1 will retrieve all fields of a relation.

class ModuleSerializer(serializers.ModelSerializer):

     class Meta:
        model = Module
        fields = ['id', 'title', 'duration', 'trainer', 'publish_choice']
        depth = 1

for reference DRF-Documentation on serializers

Sign up to request clarification or add additional context in comments.

2 Comments

@Biju consider accepting this answer if it worked for you.
Carefull with depth. If your model have more fk or many to many, depth will query all of this.
0

Its raise exception because serializers.CharField(source='trainer.username') not match ManyRelatedManager in model trainer = models.ManyToManyField(Trainer, blank=True).

If you want get all username instead of id, you can try add Custom type serialzier like this:

class ModuleSerializer(serializers.ModelSerializer):
     trainer = serializers.SerializerMethodField()

     def get_trainer(self, obj):
        results = []
        for item in obj.trainers.all():
            results.append(item.username)
        return results

     class Meta:
        model = Module
        fields = ['id', 'title', 'duration', 'trainer', 'publish_choice']

trainer will return array of username relation with Module

2 Comments

this throw the error "'Module' object has no attribute 'users'"
ah sr, i edited my answer. can you try again?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.