Python Forum

Full Version: Initializing a Serializer in init and passing data later
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.