pythondjangodjango-modelsdjango-rest-frameworkdjango-serializer

Serializing ManytoMany field in Django


I am trying to get all the tags associated with a submission. It successfully return the list of the tags when I hit the endpoint to get all the submissions but when I hit a particular submission, I get null as the values.

this is my model

class Tag(models.Model):
    title = models.CharField(max_length=50,)       

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


class Submission(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=300, null=True, blank=True)
    abstract = models.TextField(null=True, blank=True)
    comment_for_editor = models.TextField(null=True, blank=True)
    completion_status = models.BooleanField(default=False)
    tags = models.ManyToManyField("Tag", blank=True, related_name='tags')
    section = models.ForeignKey("Section", on_delete=models.CASCADE, null=True, blank=True)

this is my serializer

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['title']

class startSubmissionSerializer(serializers.ModelSerializer):
    files = SubmissionFilesSerializer(many=True, required=False)
    tags = TagSerializer(many=True, read_only=True)
    
    class Meta:
        model = Submission
        fields = ['section', 'title', 'abstract', 'comment_for_editor', 'completion_status', 'files','tags', 'id']


    def create(self, validated_data):
        user = self.context['user']
        
        files = validated_data.pop('files', [])
        tags = validated_data.pop('tags', None)

        submission = Submission.objects.create(
            author=user,
            **validated_data
        )
        
        tags = str(tags['title']).split(', ')
        print(tags)
        for tag_title in tags:
            tag, _ = Tag.objects.get_or_create(title = tag_title)
            submission.tag.add(tag)
        submission.save()
        
        
        if files != []:
            for file in files:
                SubmissionFiles.objects.create(
                    submission = submission,
                    **file
                )

        return submission

I get back all of my submissions

[ { "section": 1, "title": "New Submission 11", "abstract": "diqgduigodui", "comment_for_editor": "hodihcioshiochiohsioc", "completion_status": false, "files": [], "tags": [ { "title": 'biology" }, { "title": "english" }, { "title": "math" }, { "title": "youtube" } ], "id": 12 }, { "section": 1, "title": "New Submission 12", "abstract": "diqgduigodui", "comment_for_editor": "hodihcioshiochiohsioc", "completion_status": false, "files": [], "tags": [ { "title": "biology" }, { "title": "english" }, { "title": "math" }, { "title": "youtube" } ], "id": 13 } ]

But i get this when i hit submission/13 { "section": null, "title": null, "abstract": null, "comment_for_editor": null }

this is my view

class SubmissionView(ModelViewSet):

    """
    View your submissions
    Delete one of your submission   
    Update one of your submission
    Read one of your submission
    """

    # queryset = Submission.objects.all()
    serializer_class = startSubmissionSerializer


    def get_object(self):
        user = self.request.user
        return Submission.objects.prefetch_related('tags').filter(author=user)
    

    def get_queryset(self):
        user = self.request.user
        return Submission.objects.prefetch_related('tags').filter(author=user)
    
    
    def get_serializer_context(self):
        user = self.request.user
        return {'user': user}

Solution

  • I was able to fix the error by removing the get_object from my view

        def get_object(self):
            user = self.request.user
            return Submission.objects.prefetch_related('tags').filter(author=user)