Python Forum
Initializing a Serializer in init and passing data later
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Initializing a Serializer in init and passing data later
#1
Hi all I'm building a Forum/Subforum application in django where the Forum and Subforum both have their own models and their threads have their own models.

Here is what my constructor looks like:

class ForumFunctions:
    def __init__(self,forum_slug=None):
        if Forum.objects.filter(slug=forum_slug).exists():
            self.forum                =Forum.objects.get(slug=forum_slug)
            self.threads              =ForumThread.objects.filter(forum=self.forum)
            self.thread_cnt           =len(self.threads)
            self.thread_serializer    =NewForumThreadSerializer()
        else:
            self.forum                =SubForum.objects.get(slug=forum_slug)
            self.threads              =SubForumThread.objects.filter(forum=self.forum)
            self.thread_cnt           =len(self.threads)
            self.thread_serializer    =NewSubForumThreadSerializer()
So the serializer is going to be based on the forum type(parent or child). Right now I have a few methods in this class where I have to first check the forum type before knowing where to retrieve or send data of course. I want to remove this repetition by initializing the serializer in the init constructor and then later pass data in other methods. I feel like I've done something like this in the past but I cannot remember how. I've tried initializing the serializer with data=None and then attempting to update the key in the method below but no go.

Here is how one of my methods is written right now:

def new_forum_thread(self,data):
        if self.forum.type == "parent":
            serializer = NewForumThreadSerializer(data=data)
        else:
            serializer = NewSubForumThreadSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return serializer.data
        else:
            return serializer.errors
Reply
#2
Please disregard and delete if necessary admins.

I ended up just combining both Forum and Subforum models along with combining both thread models by using the ForeignKey "self" for reference. Something I didn't know was possible until today.

Was able to shorten my code by almost 200 lines.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Passing Request objects to a serializer in DRF Dexty 0 1,536 Aug-15-2022, 04:51 AM
Last Post: Dexty
  How to Extend a serializer in Django Rest-Framework Dexty 0 1,734 Aug-10-2022, 02:53 PM
Last Post: Dexty
  Django - Passing data from view for use client side with JavaScript in a template bountyhuntr 0 3,645 Jun-11-2018, 06:04 AM
Last Post: bountyhuntr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020