OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Serializing ManytoMany field in Django

  • Thread starter Thread starter Ayatoo
  • Start date Start date
A

Ayatoo

Guest
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

Code:
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

Code:
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

Code:
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}
<p>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.</p>
<p>this is my model</p>
<pre><code>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)

</code></pre>
<p>this is my serializer</p>
<pre><code>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
</code></pre>
<p>I get back all of my submissions</p>
<p>[
{
"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
}
]</p>
<p>But i get this when i hit submission/13
{
"section": null,
"title": null,
"abstract": null,
"comment_for_editor": null
}</p>
<p>this is my view</p>
<pre><code>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}
</code></pre>
 

Latest posts

Top