<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Caronex Labs on Medium]]></title>
        <description><![CDATA[Stories by Caronex Labs on Medium]]></description>
        <link>https://medium.com/@caronex_labs?source=rss-5550363417b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yp-pEt9bGddFqfFMFZatKg.png</url>
            <title>Stories by Caronex Labs on Medium</title>
            <link>https://medium.com/@caronex_labs?source=rss-5550363417b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:01:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@caronex_labs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generic ViewSets — Serializer Context and Hooks]]></title>
            <link>https://medium.com/django-rest-for-not-beginners/generic-viewsets-serializer-context-and-hooks-1aa0000bc71d?source=rss-5550363417b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa0000bc71d</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Caronex Labs]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 14:49:44 GMT</pubDate>
            <atom:updated>2021-12-11T08:01:36.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generic ViewSets — Serializer Context and Hooks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyzLLgKstmKa2qaIPK0Yog.png" /></figure><p>Hey there! This article is a part of a series on Django Rest Framework for people who already have experience using the framework. However, you do not need any prior context to understand this article. There are some prerequisites about Django Rest Framework itself that you must know, and I will list them out shortly.</p><p>This time, I want to address a problem that you may not face too often. When you do come across it though, it can be a little frustrating to resolve. The problem is, passing context to a serializer. Context in this context (:-p) is just some data that you may want to pass on to a serializer.</p><p>Like always, here is a list of prerequisites you will need to know about to fully appreciate the article:</p><ul><li>Generic ViewSets — You can read up the docs <a href="https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset">here</a> or our article on the topic <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-an-introduction-be8712a37e6d">here</a>.</li><li>Custom Mixins — Again, docs <a href="https://www.django-rest-framework.org/api-guide/generic-views/#creating-custom-mixins">here</a> and our article on the topic <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-custom-mixins-962e93df1de2">here</a>.</li><li>Model Serializers — You can read about it in the docs <a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer">here</a>.</li><li>Abstract User — <a href="https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html">This</a> fantastic article by SimpleIsBetterThanComplex explains it best.</li></ul><p>Knowing what you’re building makes things clearer, so let me lay the situation out. In the articles before this, we cloned the possible API behind Mediums own Profile Page. In this article however, we will be considering story creation to make the need for passing context more apparent.</p><p>Here is the current situation</p><p>The user has already filled the story in and is waiting to save the story. When he/she saves the story, a post request with all the data is sent to our API and we are responsible for saving the story under the user who sent the request.</p><p>Seems straightforward right…</p><p>Again, this series is titled, DRF for <strong>not</strong> beginners… so I’m going to gloss over the initial setup. Here is what it looks like now.</p><p>Here’s how the model would look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1cec7c70a297c19f2404b6657383f9c/href">https://medium.com/media/f1cec7c70a297c19f2404b6657383f9c/href</a></iframe><p>Here are the serializers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfb1c85ee7c4cb0b7eebb92779eb63bd/href">https://medium.com/media/bfb1c85ee7c4cb0b7eebb92779eb63bd/href</a></iframe><p>And finally, the views:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42bba2b8fc112e94e2d5a9f53626453f/href">https://medium.com/media/42bba2b8fc112e94e2d5a9f53626453f/href</a></iframe><p>If you wish to have a more in-depth view of the project, you can find it <a href="https://github.com/Caronex-Labs/DjangoRestForNotBeginners/tree/master/_1_GenericViewSets">here</a> on GitHub.</p><p>With this setup, our project now has the capability to store and return user data. Also, the ability to return all the stories authored by the current user.</p><p>Now, we begin coding the endpoint to create a new story.</p><p>We won’t need to create a new serializer, the current one will work just fine after a few modifications:</p><pre>class StorySerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Story<br>        fields = &#39;__all__&#39;<br>        <br>       # We added the following line.</pre><pre>        read_only_fields = [&#39;author&#39;, &#39;story_id&#39;]</pre><p>Earlier, this serializer was only used on a GET request, so all fields were basically read only. Now that we wish to use it for POST requests, we need to specify which fields cannot be modified.</p><p>Now let’s look at the view:</p><pre># We inherit `CreateModelMixin` in our `StoryViewSet` below.</pre><pre>class StoryViewSet(CreateModelMixin, MeMixin, GenericViewSet):<br>    serializer_class = StorySerializer<br>    permission_classes = [IsAuthenticated]</pre><pre>    def get_queryset(self):<br>        return Story.objects.all()</pre><pre>    def get_me_config(self):<br>        return {<br>            &#39;instance&#39;: self.request.user,<br>            &#39;many&#39;: False,<br>            &#39;allowed_methods&#39;: [&#39;get&#39;]<br>        }</pre><pre># This is the function we just added</pre><pre>    def create(self, request, *args, **kwargs):<br>        super(StoryViewSet, self).create(self, request, *args, **kwargs)</pre><p>This is pretty straightforward too. You don’t need to define the create function explicitly the way I have… We are going to be working in there, which is why I wanted to make it as clear as I could.</p><p>We’re almost done. The above code would have been enough if not for one tiny problem. —</p><blockquote><em>“Wait … How do you know who the author is…?”<br> — Django Developer in Distress (circa. 2020)</em></blockquote><p>What needs to be done is clear. We need to pass the user who sent the request to the serializer so that it can store that user as the author. You can do that easily by passing the user when the serializer is called:</p><p>data = StorySerializer(request.data, context={&#39;user&#39;:request.user})</p><p>The problem is… we don’t have that line in our view.</p><blockquote>“ -_- ”<br> — Django Developer in Distress (circa. 2020)</blockquote><p>And to add that single line, you will have to forego the abstraction that Django provides with CreateModelMixin. In order to combat this, Viewsets come with a method called get_serializer_context(). Here’s how that would work:</p><p>The view:</p><pre>class StoryViewSet(CreateModelMixin, MeMixin, GenericViewSet):<br>    serializer_class = StorySerializer<br>    permission_classes = [IsAuthenticated]</pre><pre>    def get_queryset(self):<br>        return Story.objects.all()</pre><pre>    def get_me_config(self):<br>        return {<br>            &#39;instance&#39;: self.request.user,<br>            &#39;many&#39;: False,<br>            &#39;allowed_methods&#39;: [&#39;get&#39;]<br>        }</pre><pre>    # The following function is what we just added</pre><pre>    def get_serializer_context(self):<br>        context = super(StoryViewSet, self).get_serializer_context()<br>        context.update({&quot;user&quot;: self.request.user})<br>        return context</pre><p>Here, we can pass data to any serializer that may be used in this viewset. In our case, we passed the user object. This will however, need to be handled on the serializer side where we add this user as the author before the object is created. Here’s how that would look:</p><p>The serializer:</p><pre>class StorySerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Story<br>        fields = &#39;__all__&#39;<br>        read_only_fields = [&#39;author&#39;, &#39;story_id&#39;]</pre><pre>        def create(self, validated_data):<br>            user = self.context[&#39;user&#39;]<br>            return Story(**validated_data, author=user)</pre><p>That was simple enough right. Infact, we actually saved a chunk of lines in the view . We don’t have to explicitly define the create method at all anymore.</p><blockquote>This is the recommended way of handling serializer context. There is a guideline beneath this method called — <em>“Skinny Controller”. <br></em>The idea is that you should keep your views thin and offload processing to either the models or the serializers to support <em>‘Separation of Concerns’. </em>In doing so, you ensure security of your data such that no outside method can directly change values inside another class.</blockquote><p>To be very honest with you… I don’t believe <em>“Skinny Controllers”</em> are a good idea when it comes to Django. In the way that I like to architect my application, my views are like the central hub. The place where all the action takes place. The major reason for this is that I assign a single viewset to deal with a single model. This way, I can encapsulate a single model, its views, its serializers and its router. Sure, other models do get involved sometimes, but that’s inevitable.</p><p>When you encapsulate your application this way, a single viewset can have multiple serializers, which is something we discuss in <a href="https://medium.com/django-rest-for-not-beginners/generic-viewset-mulitple-serializers-c490fc1382e6">this</a> article. If you offload the logic of selecting which fields to use for which call to the serializers, you break the DRY principle and repeat the same code across multiple serializers. Plus, if you want to perform more complex actions before creating the object, doing them in the view is much more convenient given the available data and methods there.</p><p>Basically, the above solution works if you have a limited number of serializers. 2 in our case. But this solution is not extremely scalable.</p><p>If this is enough for you… I’m glad I could help. I would however still request you to go through the remaining article, you might learn something you may need someday.</p><h3><strong>Hooks</strong></h3><p><strong><em>Views &gt; Serializers</em></strong></p><p>Mostly because there’s just more data and methods available to you in the view. Recognizing this, Django provides us with a comparatively lesser known set of methods called Hooks. Similar to Lifecycle Hooks you may have seen in frontend frameworks; they allow you to hook into certain automated actions performed by Django and override them. (That sounds so cool…)</p><p>There are 3 of them.</p><p>Here they are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7447219811f316376c19e41a4a7a94aa/href">https://medium.com/media/7447219811f316376c19e41a4a7a94aa/href</a></iframe><p>Let’s use the perform_create in our current code.</p><p>Let’s reset our code to before we implemented context. Here is the code now:</p><p>The Serializer:</p><pre>class StorySerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Story<br>        fields = &#39;__all__&#39;<br>        read_only_fields = [&#39;author&#39;, &#39;story_id&#39;]</pre><p>The View:</p><pre>class StoryViewSet(CreateModelMixin, MeMixin, GenericViewSet):<br>    serializer_class = StorySerializer<br>    permission_classes = [IsAuthenticated]</pre><pre>    def get_queryset(self):<br>        return Story.objects.all()</pre><pre>    def get_me_config(self):<br>        return {<br>            &#39;instance&#39;: self.request.user,<br>            &#39;many&#39;: False,<br>            &#39;allowed_methods&#39;: [&#39;get&#39;]<br>        }</pre><p>We have removed the create method from the serializer and the get_serializer_context method from the view.</p><p>Our serializer needs no changes, so let’s focus on rewriting the view.</p><p>Like I said earlier, these hooks are just methods. I believe that if you have been able to follow me till here, just showing you the code would be more than enough.</p><p>Here is our view, everything is the same apart from the last 2 lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62a53c5bad84a5709dc39e2a7817277a/href">https://medium.com/media/62a53c5bad84a5709dc39e2a7817277a/href</a></iframe><p>And that’s it.</p><p>No serializer context function. No create method in the serializer. No explicit create method in your view.</p><p>And the best part comes now. If you have been following the series, you know that the user model has a field that keeps a count of the number of articles the user has written. For demonstration purposes, we are not calculating that dynamically like we should. So… here is something you can do now that we are using a hook:</p><pre>class StoryViewSet(CreateModelMixin, MeMixin, GenericViewSet):<br>    serializer_class = StorySerializer<br>    permission_classes = [IsAuthenticated]</pre><pre>def get_queryset(self):<br>        return Story.objects.all()</pre><pre>def get_me_config(self):<br>        return {<br>            &#39;instance&#39;: self.request.user,<br>            &#39;many&#39;: False,<br>            &#39;allowed_methods&#39;: [&#39;GET&#39;]<br>        }</pre><pre>def perform_create(self, serializer):<br>        serializer.save(author=self.request.user)<br>        self.request.user.articles += 1<br>        self.request.user.save()</pre><p>You can do limitless computation before you save the serializer, while having access to the data and methods inside your view.</p><p>It’s pretty fantastic.</p><p>This article actually brings us to the end of our series on Generic Viewsets. I hope that I was able to help somehow and maybe even introduce you to new and easier ways to solve problems using Django.</p><p>This is not the end at all though. After a short break, we are going to have another series under the same publication but this time we will explore Routers.</p><p>Before I end, I would like to tell all of you that when we write articles for a series of blogs, we cut a lot of corners to focus on the important parts… or at least I did. Most times it doesn’t matter too much because the reader knows how to fit what they read here into their own projects. However, if there is any part that you believe needs clarification. Please feel free to reach out to us. And with that…</p><blockquote>Thank you, and as always… stay tuned.</blockquote><blockquote>- Django Developer Not in Distress (circa. 2020)</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FbSQQeX0Eq04YuBW0nr%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FbSQQeX0Eq04YuBW0nr%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FbSQQeX0Eq04YuBW0nr%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="314" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c28e19c1ec300d5f6c5ea1ee949a89d/href">https://medium.com/media/0c28e19c1ec300d5f6c5ea1ee949a89d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa0000bc71d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-serializer-context-and-hooks-1aa0000bc71d">Generic ViewSets — Serializer Context and Hooks</a> was originally published in <a href="https://medium.com/django-rest-for-not-beginners">Django Rest for Not Beginners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generic ViewSet— Mulitple Serializers]]></title>
            <link>https://medium.com/django-rest-for-not-beginners/generic-viewset-mulitple-serializers-c490fc1382e6?source=rss-5550363417b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c490fc1382e6</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Caronex Labs]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 10:32:07 GMT</pubDate>
            <atom:updated>2021-12-20T02:22:33.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generic ViewSets— Mulitple Serializers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5e4nIjnfyQTnmd9YUN6mQ.png" /></figure><p>Hey there! In this article, we will be exploring ways in which we can hook up multiple serializers in a single ViewSet. This article is actually a part of a series that you can find <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets/home"><strong>here</strong></a>. However, you do not need any prior context if you are using this article just as a reference. With that introduction, let’s get started.</p><p>Like every time, here is a list of prerequisites you should be familiar with to properly appreciate this article:</p><ul><li>Generic ViewSets — You can check out the <a href="https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset"><strong>docs</strong></a> or our <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-an-introduction-be8712a37e6d"><strong>article</strong></a> here.</li><li>Custom Endpoints — Again, the <a href="https://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing"><strong>docs</strong></a>… or our article <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-custom-endpoints-5e746210173f"><strong>here</strong></a>.</li><li>Custom Mixins — Not completely required, but you’ll be more aware of what’s happening. We have an article on this <strong>here</strong>. Find the docs <a href="https://www.django-rest-framework.org/api-guide/generic-views/#customizing-the-generic-views"><strong>here</strong></a>.</li><li>AbstractUser — Not completely required, but you’ll be more aware of what’s happening. Find the docs <a href="https://docs.djangoproject.com/en/3.0/topics/auth/customizing/"><strong>here</strong></a>.</li><li>ModelSerializers. Find the docs <a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer"><strong>here</strong></a>.</li></ul><h3>The Aim:</h3><p>Alright then, before we begin, let’s have a look at what we hope to build:</p><p>Just a reminder of our primary goal. <strong>We are building a REST API Backend for the Profile Page of Medium</strong>. This One:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pOID_f8_fUE92CMo_I8Dg.jpeg" /></figure><p>As you may have noticed, we do have some new fields here as well. Namely, the Last Edited and the Articles fields.</p><p>In the last few articles, we built the ViewSets that allow us to retrieve the <strong>users profile information</strong> and the <strong>users articles. </strong>We used custom endpoints and custom mixins to achieve the same, you can go through these articles <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets/home"><strong>here</strong></a> if you wish to have a closer look.</p><p>Again, if you’re just using this as a reference, please don’t worry too much about the context. The code below is what we have completed as of now and it should be enough to get all of us on the same page.</p><p><strong>The Model:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a3d2edda68b1268cfbf79e2fdc13c1/href">https://medium.com/media/c3a3d2edda68b1268cfbf79e2fdc13c1/href</a></iframe><p><strong>The Views:</strong></p><p>This one is a little more complex, but I’m sure you’ll get it. Just give it a good read.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0d3a26e94ca929e52ccae8c5f3149f1/href">https://medium.com/media/e0d3a26e94ca929e52ccae8c5f3149f1/href</a></iframe><p><strong>The Serializers:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0079c4283e94061ab617864b82dababa/href">https://medium.com/media/0079c4283e94061ab617864b82dababa/href</a></iframe><p><strong>The URLs:</strong></p><p>We should almost always use routers when building URLs. For simplicity, we have built our endpoints this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3963d5e8767be684e259325eefc79c24/href">https://medium.com/media/3963d5e8767be684e259325eefc79c24/href</a></iframe><p>If you wish to get an even clearer idea of the project, you can check it out <a href="https://github.com/Caronex-Labs/DjangoRestForNotBeginners/tree/master/_1_GenericViewSets"><strong>here</strong></a> on <strong>GitHub</strong>.</p><p>Now that everyone’s on the same page, let’s have a look at where we go next.</p><p>This time, we are going to build the Edit Profile option. This will entail the following:</p><ul><li>Update the serializer to allow only certain fields to be edited.</li><li>Add an endpoint to change the <em>Profile Picture</em>, <em>Twitter Profile URL</em>, <em>Profile Name</em> and <em>Bio</em>.</li><li>Add the <em>Last Edited </em>to reflect the change<em>.</em></li><li>Make the way the serializer is selected more scalable. (This will become clearer soon.)</li><li>Convert the endpoint to a Mixin to make it more scalable as well.</li></ul><p>Alright then, let’s go through the above points one by one.</p><h3>1. Updating The Serializer -</h3><p>Now that we have fields which should not be edited, we will have to mark them as read-only . You should already be familiar with this if you’ve come this far, so I’m just going to show the new serializer here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06f6a111286493df4a12a5574cd39879/href">https://medium.com/media/06f6a111286493df4a12a5574cd39879/href</a></iframe><blockquote><strong>Just a reminder</strong>: Some of the read-only fields might seem out of place, but that’s because <strong>we’re building this backend just for the profile page</strong>. We will only consider what we are allowed to edit from there.</blockquote><h3>2. Adding the Endpoint -</h3><p>The most optimum course of action is to add this functionality inside of the me endpoint. But in order to gain a better understanding of how things work, we will get there in smaller steps.</p><p>Let’s first start by building a patch endpoint that only works on the current user.</p><p>This is what that endpoint would look like:</p><pre>from datetime import date</pre><pre>class UserViewSet(MeMixin, GenericViewSet):<br>    ...</pre><pre><em><br>    def </em>patch(<em>self</em>, request, *args, **kwargs):<br>        serializer = <em>self</em>.get_serializer_class()<br>        user = User.objects.get(user_id=request.user.user_id)<br>        data = serializer(user, request.data, partial=<em>True</em>)<br>        data.is_valid(raise_exception=<em>True</em>)<br>        data.save()<br>        <em>return </em>Response({<br>            &#39;message&#39;: &quot;User Profile Updates&quot;<br>        },<br>            status=status.HTTP_200_OK,<br>        )</pre><p>Let’s break the above function down:</p><ul><li>The name patch is a reserved name that instructs the viewset to call this function if a patch request is sent to the base URL of the viewset.</li><li>By calling the serializer and passing the current user, the data of the request and the keyword partial , we are telling the serializer that — Take this user, and the data we have received, and try to update the user with that data. It also indicates that we need to update the user partially, meaning that we only need to update the fields passed in the request… leave the others untouched.</li><li>The is_valid(raise_exception=True) function checks if the serializer was able to perform the requested patch. By passing raise_exception we tell the serializer to automatically create a Bad Request response and return it to the frontend. This way we don’t have to create a failure Response manually.</li><li>data.save() is the function that finally performs the patching and updates the database to reflect the changes.</li><li>We are not updating the last_edited . Let’s fix that in a minute.</li></ul><h3>3. Add The Last_Edited Field</h3><p>To store last_edited → <br>We will make a change in the models, make the following change to the User Model -</p><pre><em>class </em>User(AbstractUser):<br>    <em># The following fields are declared by Django by default.<br>    # I have mentioned them just so that there is no doubt.<br><br>    </em>user_id = models.AutoField(primary_key=<em>True</em>)<br>    username = models.CharField(max_length=100, unique=<em>True</em>)<br>    email = models.EmailField(unique=<em>True</em>)<br>    first_name = models.CharField(max_length=100)<br>    last_name = models.CharField(max_length=100)<br><br>    <em># The following fields are the custom fields.<br><br>    </em>bio = models.TextField(blank=<em>True</em>)<br>    headline = models.CharField(max_length=300)<br>    following = models.IntegerField(default=0)<br>    articles = models.IntegerField(default=0)<br>    profile_picture = models.URLField(blank=<em>True</em>)</pre><pre>    # The following field is what we just added.</pre><pre>    last_edited = models.DateTimeField(auto_now=<em>True</em>)</pre><p>This way, every time a user object is saved, the last_edited field will automatically get updated.</p><p>Make sure to add the last_edited field to the read_only fields in your serializer.</p><p>Before we move on to the next part, let’s catch a breather and make sure we’re all on the same page.</p><p>Here are the pages that we have made changes to since the beginning of this article.</p><h4>Models</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a3d2edda68b1268cfbf79e2fdc13c1/href">https://medium.com/media/c3a3d2edda68b1268cfbf79e2fdc13c1/href</a></iframe><h4>Views</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f66735af9ec1992399a873cb564ebbe0/href">https://medium.com/media/f66735af9ec1992399a873cb564ebbe0/href</a></iframe><h4>Serializers</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/018bc043f1edb831cce5d211f8258d02/href">https://medium.com/media/018bc043f1edb831cce5d211f8258d02/href</a></iframe><p>We’re lucky in that this code works. The two endpoints we have right now, patch and me , use the same serializer. The only difference being that one uses the PATCH method while the other uses the GET method.</p><p>By adding read-only fields to our serializer, we can make the same serializer work for both these cases. But… what do you do when multiple endpoints in the same viewset need different serializers?</p><p>Let’s find out…</p><h3>4. Make The Serializer Selection Scalable</h3><p>Generic ViewSets come with the get_serializer_class() function. This function returns the serializer class that should be used by a endpoint inside of that viewset.</p><p>We are already using this function inside our endpoints. We call the self.get_serializer_class() to get the serializer class that we need to use for the current endpoint.</p><p>So, we will just tweak that inbuilt function a bit, to suite our needs.</p><p>The new get_serializer_class() function:</p><pre><em>class </em>UserViewSet(MeMixin, GenericViewSet):<br>    ...<br><br>    <em>def </em>get_serializer_class(<em>self</em>):<br>        if self.action == &#39;me&#39;:<br>            if self.request.method == &#39;GET&#39;:<br>                return UserSerializer<br>        else:<br>            if self.request.method == &#39;PATCH&#39;:<br>                return UserSerializer</pre><p>It might seem… useless… but this is just an example. This is how you would do it if there were actually 2 different serializers.</p><p>Let’s break it down:</p><ul><li>Most importantly, what this function returns will be the serializer that will be used. This is the key to modifying the function to do whatever you might need.</li><li>There are two keywords we have used here that may be new to you:<br>- self.action — This is the name of the endpoint being called. It is literally the name of the function that links to the endpoint. However, if you use the function on the base URL, the way we have done with patch() , it does not return a self.action <br>- self.request.method — Returns the HTTP method being called.</li><li>Again, we’re returning the same serializer in both cases, but this is to show you how it is to be done.</li></ul><p>In order for this to work, we will have to update our URLs as well:</p><pre><em>from </em>django.contrib <em>import </em>admin<br><em>from </em>django.urls <em>import </em>path<br><em>from </em>rest_framework.authtoken.views <em>import </em>obtain_auth_token<br><br><em>from </em>users_module.views <em>import </em>UserViewSet<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),</pre><pre>   # We edited the following endpoint:</pre><pre>    path(&#39;users/me&#39;, UserViewSet.as_view({&#39;get&#39;: &#39;me&#39;, &#39;patch&#39;: &#39;patch&#39;}), name=&quot;user_view_set&quot;),</pre><pre>    path(&#39;api-token-auth/&#39;, obtain_auth_token,  name=&#39;api_token_auth&#39;),  <em># &lt;-- And here<br><br></em>]</pre><p>If you’ve read any of the previous article, I have this habit of making code and then calling it ugly…</p><p><em>It’s ugly.</em></p><p>This works, but I happen to have developed a coding pattern that makes this look even better. Whatever you read beyond this is completely optional to do. But if you’re interested… here we go.</p><p>You know what would make this code really really clean?</p><p>Switch Case</p><p>But python does not have switch case…</p><p>So here’s the solution.</p><p>Let’s create a python dictionary that stores the serializer we wish to call for every endpoint.</p><p>It’ll look something like this :</p><pre>viewset_serializers = {<br>    &#39;me&#39; : UserSerializer,<br>    &#39;patch&#39; : UserSerializer<br>}</pre><p>and now, our get_serializer_class() function is reduced to:</p><pre><em>def </em>get_serializer_class(<em>self</em>):<br>    <em>return self</em>.viewset_serializers.get(<em>self</em>.action)</pre><p>So much better…</p><p>This is as scalable as we can make our serializer selection for now. Any time you have a new endpoint, just add an entry in the viewset_serializers variable, and you’re done.</p><p>However, our patch endpoint is a little confusing. You should avoid using the method names directly. They work, but they will confuse you eventually. Instead, if you want to use HTTP calls on the base URL, just use the inbuilt mixins (UpdateModelMixin, CreateModelMixin, etc) and edit the functions that come with it.</p><p>For now, we’re gonna do one last thing. We’re gonna move our patch request into our me endpoint. Because it would make more sense to call the patch on the me endpoint to update the current user.</p><h3>5. Convert the endpoint to a Mixin</h3><p>Let’s start by simply moving our patch logic into the MeMixin and solve any issues we face.</p><p>The MeMixin :</p><pre><em>class </em>MeMixin:<br><br>    @action(methods=[&#39;get&#39;, &#39;patch&#39;], detail=<em>False</em>)<br>    <em>def </em>me(<em>self</em>, request):<br>        serializer = <em>self</em>.get_serializer_class()<br><br>        <em>if </em>request.method == &#39;GET&#39;:<br><br>            data = serializer(<br>                instance=<em>self</em>.get_me_config().get(&#39;instance&#39;),<br>                many=<em>self</em>.get_me_config().get(&#39;many&#39;)<br>            ).data<br>            <em>return </em>Response(data, status=status.HTTP_200_OK)<br><br>        <em>elif </em>request.method == &#39;PATCH&#39;:<br>            <br>            user = User.objects.get(user_id=request.user.user_id)<br>            data = serializer(user, request.data, partial=<em>True</em>)<br>            data.is_valid(raise_exception=<em>True</em>)<br>            data.save()<br>            <em>return </em>Response({<br>                &#39;message&#39;: &quot;User Profile Updated&quot;<br>            },<br>                status=status.HTTP_200_OK,<br>            )</pre><p>Here’s the breakdown:</p><ul><li>We added‘patch’ to the allowed methods for the me endpoint. Check the action decorator .</li><li>We added an if-else statement to perform two separate logic depending on the HTTP method called.</li></ul><p>And here we face our first issue. We’re calling the get_serializer_class() which we haven’t updated to reflect this new change. So let’s do that.</p><p>First, we will have to update the structure of the viewset_serializers variable because we now have two different endpoints under the same function.</p><pre>viewset_serializers = {<br>    &#39;me&#39; : {<br>              &#39;get&#39; : UserSerializer,<br>              &#39;patch&#39; : UserSerializer<br>           } <br>}</pre><p>This is an interesting change, and I hope you see how this is going to allow us to scale the serializer selection even more now.</p><p>In accordance to this change, we will also edit the get_serializer_class() function.</p><pre><em>def </em>get_serializer_class(<em>self</em>):<br>    <em>return self</em>.viewset_serializers.get(<em>self</em>.action).get(self.request.method)</pre><p>This is where we face our second problem. We are using our MeMixin in both our viewsets, but our StoryViewSet doesn’t have a patch method.</p><blockquote>If you aren’t following the series, this part probably won’t make as much sense. I do recommend giving it a read however, it’ll help you realize how to twist and manipulate our code to accommodate any requirements you may have.</blockquote><p>We already have a get_me_config() function in both our viewsets . We will make use of them to deal with this problem.</p><p>We will include a allowed_methods list in this config that allows us to list down the allowed methods for both the viewsets individually:</p><p>The UserViewSet get_me_config() function:</p><pre><em>def </em>get_me_config(<em>self</em>):<br>    <em>return </em>{<br>        &#39;instance&#39;: <em>self</em>.request.user,<br>        &#39;many&#39;: <em>False,<br>        &#39;</em>allowed_methods&#39; : [&#39;get&#39;, &#39;patch&#39;]<em><br>    </em>}</pre><p>Similarly, the StoryViewSet get_me_config() function:</p><pre><em>def </em>get_me_config(<em>self</em>):<br>    <em>return </em>{<br>        &#39;instance&#39;: <em>self</em>.request.user,<br>        &#39;many&#39;: <em>False,<br>        &#39;</em>allowed_methods&#39; : [&#39;get&#39;]<em><br>    </em>}</pre><p><em>I really hope you already see where we are going with this…</em></p><p>We will now update our MeMixin to reflect this change.</p><p>MeMixin :</p><pre><em>class </em>MeMixin:<br><br>    @action(methods=[&#39;get&#39;, &#39;patch&#39;], detail=<em>False</em>)<br>    <em>def </em>me(<em>self</em>, request):<br>        serializer = <em>self</em>.get_serializer_class()<br><br>        <em>if </em>request.method == &#39;GET&#39; <em>and </em>&#39;GET&#39; <em>in self</em>.get_me_config().get(&#39;allowed_methods&#39;):<br><br>            data = serializer(<br>                instance=<em>self</em>.get_me_config().get(&#39;instance&#39;),<br>                many=<em>self</em>.get_me_config().get(&#39;many&#39;)<br>            ).data<br>            <em>return </em>Response(data, status=status.HTTP_200_OK)<br><br>        <em>elif </em>request.method == &#39;PATCH&#39; <em>and </em>&#39;PATCH&#39; <em>in self</em>.get_me_config().get(&#39;allowed_methods&#39;):<br>            user = User.objects.get(user_id=request.user.user_id)<br>            data = serializer(user, request.data, partial=<em>True</em>)<br>            data.is_valid(raise_exception=<em>True</em>)<br>            data.save()<br>            <em>return </em>Response({<br>                &#39;message&#39;: &quot;User Profile Updated&quot;<br>            },<br>                status=status.HTTP_200_OK,<br>            )<br><br>        <em>else</em>:<br>            <em>return </em>Response({<br>                &#39;message&#39;: f&quot;Unsupported method {request.method}.&quot;,<br>            },<br>                status=status.HTTP_400_BAD_REQUEST<br>            )</pre><p>Here’s the breakdown:</p><ul><li>In both our if conditions, we now check if the method is present in the allowed_methods of the get_me_config() .</li><li>We added an else condition to return an error if an unsupported method is used.</li></ul><p>You will have to edit your URLs to reflect this change as follows:</p><pre><em>from </em>django.contrib <em>import </em>admin<br><em>from </em>django.urls <em>import </em>path<br><em>from </em>rest_framework.authtoken.views <em>import </em>obtain_auth_token<br><br><em>from </em>users_module.views <em>import </em>UserViewSet<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),</pre><pre>    # We edited the following endpoint so that both methods point to the &#39;me&#39; endpoint.  </pre><pre>    path(&#39;users/me&#39;, UserViewSet.as_view({&#39;get&#39;: &#39;me&#39;, &#39;patch&#39;: &#39;me&#39;}), name=&quot;user_view_set&quot;),</pre><pre>    path(&#39;api-token-auth/&#39;, obtain_auth_token, name=&#39;api_token_auth&#39;),  <em># &lt;-- And here<br><br></em>]</pre><p>Well… that was a lot. But it was definitely worth it. Let’s look at our code now and you’ll see why.</p><p>Our application is besides the point here. So when you look at the code, think of how it would work on a large scale project. How much code and confusion it would save on a project you’ve recently worked on.</p><h4>Views</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be1d567cfebfd6ca2178435e4cca5148/href">https://medium.com/media/be1d567cfebfd6ca2178435e4cca5148/href</a></iframe><p>Anytime you wish to add a new endpoint:</p><ul><li>Create the serializer</li><li>Add it to the viewset_serializers</li><li>Create the function</li></ul><p>Well… that is how you deal with multiple serializers in a single viewset . Just a reminder… creating a dictionary to store the serializers is something we have come up with and it’s a very young idea. I’m sure you will find ways to make this even better. If you do, please do share it in the comments here or on any of our social media. We would love to improve this pattern.</p><p>That’s it for this time, We hope this helps you improve your code. If you have any questions, ask away… we would love to help you out.</p><p>Until next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c490fc1382e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-rest-for-not-beginners/generic-viewset-mulitple-serializers-c490fc1382e6">Generic ViewSet— Mulitple Serializers</a> was originally published in <a href="https://medium.com/django-rest-for-not-beginners">Django Rest for Not Beginners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generic ViewSets — Custom Mixins]]></title>
            <link>https://medium.com/django-rest-for-not-beginners/generic-viewsets-custom-mixins-962e93df1de2?source=rss-5550363417b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/962e93df1de2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Caronex Labs]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 12:54:43 GMT</pubDate>
            <atom:updated>2021-12-11T07:45:05.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generic ViewSets — Custom Mixins</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1D7pXgtKdaJCvxo333Uug.png" /></figure><p><strong>Welcome back! </strong>or <strong>Hey there! </strong>depending on whether you’re following the <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets/home"><strong>series</strong></a> or using this as a reference… both of which is perfectly alright by the way, you don’t need a lot of context to understand the crux of this article.</p><p>If you really only want to see the syntax or the rudimentary application of a mixin, just scroll all the way down to <strong>Step 3: The Mixin. </strong>It’s towards the end of the article.</p><h3>So let’s get started!</h3><p>Like every time, here is a list of prerequisites that you should be familiar to truly appreciate this article:</p><ul><li>Generic ViewSets — You can check out the <a href="https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset"><strong>docs</strong></a> or our <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-an-introduction-be8712a37e6d"><strong>article</strong></a> here.</li><li>Custom Endpoints — Again, the <a href="https://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing"><strong>docs</strong></a>… or our article <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-custom-endpoints-5e746210173f"><strong>here</strong></a>.</li><li><a href="https://docs.djangoproject.com/en/3.0/topics/auth/customizing/"><strong>AbstractUser</strong></a> — Not completely required, but you’ll be more aware of what’s happening.</li><li><a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer"><strong>ModelSerializers</strong></a>.</li></ul><p>Do consider paying a visit to <a href="https://medium.com/django-rest-for-not-beginners"><strong>our publication</strong></a> if you wish to understand the project thoroughly.</p><p>I believe that the best place to start is to see where we want to end up, so…</p><h3><strong>Here’s our aim</strong>:</h3><p>We’re trying to replicate Medium’s profile page backend.</p><p>Which means we need to retrieve and update the users information and their stories. We’re avoiding anything too complicated, so don’t worry about this too much.</p><p>This time, we will build the endpoints to retrieve the current users Stories and then create a mixin to reduce code.</p><p>Here is the page we are building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCe3quU4tAK3QPkNU-Awvw.png" /></figure><h3>Some Background:</h3><p>Last time, we created a custom endpoint and called it the me endpoint. It returned the data of the current user. Here is the view, the serializer, the model and the urls for the same. Just go through it, we don’t need to be familiar with every bit of this code:</p><h4>The Model:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03609f79d77a78b36643973594f9c49e/href">https://medium.com/media/03609f79d77a78b36643973594f9c49e/href</a></iframe><h4>The View:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e5bb2768ccedfbb8ccbebbb1a5c5e64/href">https://medium.com/media/1e5bb2768ccedfbb8ccbebbb1a5c5e64/href</a></iframe><h4>The Serializer:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a8b35afa6b7aa1c085409294ae6013a/href">https://medium.com/media/4a8b35afa6b7aa1c085409294ae6013a/href</a></iframe><h4>The URLs:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3963d5e8767be684e259325eefc79c24/href">https://medium.com/media/3963d5e8767be684e259325eefc79c24/href</a></iframe><blockquote>If you really wish to understand the project better, here it is on <a href="https://github.com/Caronex-Labs/DjangoRestForNotBeginners/tree/master/_1_GenericViewSets"><strong>Github</strong></a>.</blockquote><h3>Let’s Start:</h3><p>Now that everyone is on the same page, let’s get to what we want to do:</p><ul><li>Introduce the Stories Model.</li><li>Create an endpoint to get the current users stories.</li><li>Create a custom mixin to reduce the amount of code.</li></ul><h4>Step 1: The Model -</h4><p>…<em> The title of this series is Django Rest For </em><strong><em>NOT</em></strong><em> Beginners…</em></p><p>Here it is :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91515da29a31b5f22be59e8d67e6df01/href">https://medium.com/media/91515da29a31b5f22be59e8d67e6df01/href</a></iframe><blockquote><strong>Pro Tip:</strong></blockquote><blockquote>A Meta class is a class, generally inside another class, that contains metadata about the parent class.</blockquote><blockquote>The default behavior of Django is to just add an ‘s’ at the end of the name of the model to get the plural name.</blockquote><blockquote>In our case, we are using the Meta class to edit the metadata -the plural form of the name of this model. You can also use the Meta class to modify other metadata like ordering or db_index.</blockquote><blockquote>This change is purely cosmetic, it will make the name of the model appear properly in the Admin Panel that comes with Django.</blockquote><h4>Step 2: The Endpoint -</h4><p>We’ve got our model in place, now let’s look at the view. We will be creating a new Generic ViewSet for our stories.</p><p><strong>This is what it looks like:</strong></p><p>The Serializer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeba13d5fb2f4e5bf7d36611aa560af8/href">https://medium.com/media/aeba13d5fb2f4e5bf7d36611aa560af8/href</a></iframe><p>The View:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7e9c9367d19aabd7f233b2e848d5781/href">https://medium.com/media/b7e9c9367d19aabd7f233b2e848d5781/href</a></iframe><p>Let’s break it down:</p><ul><li>We added a new Serializer called StorySerializer. It’s a simple ModelSerializer.</li><li>We added a new ViewSet called StoryViewSet.</li><li>We created a custom endpoint called me that returns the current users stories. In order to do that:<br>- We got our serializer<br>- We passed in the current user’s stories (We used the related name that links the User model to the Stories model)<br>-We mentioned many=True that tells the serializer to expect multiple objects, because each user could have authored multiple stories.</li><li>We returned the desired data as a Response</li></ul><p>Notice how the two me endpoints are really similar. We are violating a very important principle of development: <strong>DRY. </strong>It stands for <strong>Don’t Repeat Yourself. </strong>And that is what we will try to fix now.</p><p>So, lets try to make both the me functions the same. Again, <strong>in steps</strong>.</p><ol><li><strong>Find the difference between the two functions.</strong></li></ol><p>The two me functions differ by only a single line. This one: data=serializer(request.user).data — UserViewSet<br>data=serializer(request.user.stories, many=True) — StoryViewSet</p><p>Even in this line, there’s really two things that differ. They are the arguments that we pass to the serializer.<br> — To be able to change these arguments dynamically, we must first understand what they are.</p><p>2.<strong> Understand the arguments.</strong></p><p>A serializer takes many arguments. We perhaps delve into them in a later series. But what concerns us now are the instance and the many arguments.</p><ul><li>The instance takes in an object that needs to be serialized.</li><li>The many argument is a boolean that indicates if we are passing a single object or a list of objects (A Queryset).</li></ul><p>3. <strong>Abstract the arguments away.</strong></p><p>Let’s get to the coding part.</p><p>First thing we must do is to create variables out of the arguments we pass.</p><p>This can get a little confusing, so try to code along. That always helps me understand.</p><ul><li><strong>Create Variables Out Of Arguments:</strong></li></ul><p>Right now, we are passing data to our serializers directly. Which is causing the two me functions to be different. Which is why, we will now pass the data indirectly through variables.</p><pre><em># The UserViewSet me Endpoint</em></pre><pre>@action(methods=[&#39;get&#39;], detail=False)    <br>def me(self, request):        <br>    serializer = self.get_serializer_class()<br>    <br>    instance = request.user<br>    many = False        <br>    <br>    data = serializer(instance = instance, many = many).data        <br>    return Response(data, status=status.HTTP_200_OK)</pre><pre><em># The StoryViewSet me Endpoint</em></pre><pre>@action(methods=[&#39;get&#39;], detail=False)    <br>def me(self, request):        <br>    serializer = self.get_serializer_class()<br>    <br>    instance = request.user.stories<br>    many = True        <br>    <br>    data = serializer(instance = instance, many = many).data<br>    return Response(data, status=status.HTTP_200_OK)</pre><ul><li><strong>Take those variables out of the function and make them properties of the parent class. The use the </strong><strong>self keyword to access them.</strong></li></ul><pre>class UserViewSet(GenericViewSet):<br>    ...<br>    <br>    instance = request.user<br>    many = False</pre><pre>@action(methods=[&#39;get&#39;], detail=False)    <br>    def me(self, request):        <br>        serializer = self.get_serializer_class()<br>    <br>        data = serializer(<br>                          instance = self.instance, <br>                          many = self.many<br>                         ).data       <br>        <br>        return Response(data, status=status.HTTP_200_OK)</pre><pre><br>class StoryViewSet(GenericViewSet):<br>    ...</pre><pre>    instance = request.user.stories<br>    many = True</pre><pre>@action(methods=[&#39;get&#39;], detail=False)    <br>    def me(self, request):        <br>        serializer = self.get_serializer_class()<br>    <br>        data = serializer(<br>                          instance = self.instance, <br>                          many = self.many<br>                         ).data<br>        <br>        return Response(data, status=status.HTTP_200_OK)</pre><p>We’ve got ourselves an identical me function. <strong>Yay!</strong></p><p>But the above code won’t run just yet. The issue is that you cannot access the request keyword outside a function. So how do we assign the instance as request.user.</p><p>To solve this problem, we will create a function inside each of the two ViewSets. This function simply returns the above two variables inside a dictionary. Let’s call this function: get_me_config because, that’s what we’re doing… configuring the me function.</p><p>Here is what the function will look like:</p><pre><em># This is for the UserViewSet</em></pre><pre>def get_me_config(self):<br>    return {<br>             &#39;instance&#39;: self.request.user,<br>             &#39;many&#39; : False <br>           }</pre><p>And now our me function will have to be modified like this:</p><pre><em># This is for the UserViewSet but now the function is same for both</em></pre><pre>@action(methods=[&#39;get&#39;], detail=False)    <br>    def me(self, request):        <br>        serializer = self.get_serializer_class()<br>    <br>        data = serializer(<br>                    instance=self.get_me_config().get(&#39;instance&#39;), <br>                    many = self.get_me_config().get(&#39;many&#39;)<br>                         ).data        <br>        <br>        return Response(data, status=status.HTTP_200_OK)</pre><p><strong>And we’re done with the abstraction.<br></strong>Both our me functions are now identical.</p><h4>This has been heavy. So let’s take a breather.</h4><p>Here is our final code after all the changes we just made:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3eebe056f9f65663e4383ce173368c/href">https://medium.com/media/6e3eebe056f9f65663e4383ce173368c/href</a></iframe><p>So simple it looks right… after all the pain we just went through.</p><p>The me function is now clearly repeated. Let’s get rid of the repetition.</p><h4>Step 3: The Mixin -</h4><p>Well, after that life changer… turns out that, ironically, this section is the easiest… even though it’s the whole reason you are reading this article.</p><p>Making a mixin is really simple. Here are the steps</p><ul><li>Make a class.</li><li>Copy the repeating code.</li><li>Include this new class in the ViewSet.</li></ul><p>So let’s begin.</p><ol><li><strong>Make A Class</strong></li></ol><pre>class MeMixin:<br>    </pre><p>Done.</p><p><strong>2. Copy The Repeating Code</strong></p><pre>class MeMixin:<br>    <br>    @action(methods=[&#39;get&#39;], detail=False)    <br>    def me(self, request):        <br>        serializer = self.get_serializer_class()         <br>        data = serializer(<br>            **self.get_me_config()<br>          ).data         <br>        return Response(data, status=status.HTTP_200_OK)</pre><blockquote>Pro Tip: using ** before a dictionary or a function call that returns a dictionary will basically allow the function to use the dictionary contents as arguments.</blockquote><p>Done.</p><p><strong>3. Include The New </strong><strong>Mixin in the </strong><strong>ViewSet</strong></p><pre>class UserViewSet(MeMixin, GenericViewSet):    </pre><pre>    serializer_class = UserSerializer    <br>    permission_classes = [IsAuthenticated]     </pre><pre>    def get_queryset(self):        <br>        return User.objects.all()</pre><p><strong>Ta-da!</strong></p><p>This time we’re done for real.</p><p>Here is the final code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0d3a26e94ca929e52ccae8c5f3149f1/href">https://medium.com/media/e0d3a26e94ca929e52ccae8c5f3149f1/href</a></iframe><p>Does this look good? : <em>Yes</em></p><p>Was it worth the pain? : <em>Probably</em></p><p>This situation was probably not one in which you would consider using a custom mixin. We didn’t save a whole bunch of lines by doing what we did.</p><p>But I chose this example because the relative ease of the aim let us focus on what was really important. <strong>Creating a </strong><strong>Mixin and messing around with it.</strong></p><p>This one was probably a little more complex than the other articles we’ve been through and I hope I was able to convey the information across well.</p><p>Let’s wrap it up here. Next time, we will work multiple serializers in a single viewset. I hope to see you there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=962e93df1de2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-custom-mixins-962e93df1de2">Generic ViewSets — Custom Mixins</a> was originally published in <a href="https://medium.com/django-rest-for-not-beginners">Django Rest for Not Beginners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generic ViewSets — Custom Endpoints]]></title>
            <link>https://medium.com/django-rest-for-not-beginners/generic-viewsets-custom-endpoints-5e746210173f?source=rss-5550363417b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e746210173f</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[drf]]></category>
            <dc:creator><![CDATA[Caronex Labs]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 13:04:30 GMT</pubDate>
            <atom:updated>2022-01-16T06:18:04.543Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generic ViewSets — Custom Endpoints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suDh-6srtgOTpjl8MXPf0w.png" /></figure><p>Welcome back! For those of you who are new here, this article is a part of a series that you may check out <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets/home"><strong>here</strong></a>. However, you don’t need a lot of context if you’re using this as a reference.</p><p>Let’s get started… here are a <strong>list of things you should be familiar with:</strong></p><ul><li><a href="https://www.django-rest-framework.org/api-guide/viewsets/#genericviewset">Generic ViewSets</a></li><li><a href="https://docs.djangoproject.com/en/3.0/topics/auth/customizing/">AbstractUser</a></li><li><a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer">ModelSerializer</a></li></ul><p>You can go through <a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-an-introduction-be8712a37e6d"><strong>this</strong></a> article if you want a quick refresher.</p><h4>First, our aim:</h4><p>Last time, we created our <strong>User model</strong>, <strong>User Serializer</strong> and our <strong>UserViewSet</strong>. The project is on Github <a href="https://github.com/Caronex-Labs/DjangoRestForNotBeginners/tree/master/_1_GenericViewSets"><strong>here</strong></a>. Again, if you’re not following the series, don’t panic, you don’t need to know the setup to understand the topic.</p><p>Today, our aim is to <strong>create a custom endpoint</strong> for retrieving the current users information.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXyaQAnihoZBU3GmFPl%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXyaQAnihoZBU3GmFPl%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FXyaQAnihoZBU3GmFPl%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbea2c5877b3a01f51e7cf128d592c91/href">https://medium.com/media/cbea2c5877b3a01f51e7cf128d592c91/href</a></iframe><p>Let’s start with the <strong>Custom Endpoint, </strong>here is how we’re coding our endpoint right now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2d5b7e774ab9b466d66707dc9b114c/href">https://medium.com/media/cd2d5b7e774ab9b466d66707dc9b114c/href</a></iframe><p>Even though this is much cleaner than using a ModelViewSet, it’s still not optimum.</p><ul><li>For one, we are defining a queryset that is meant to return exactly one user. That’s the opposite of what a query-SET is meant to do.</li><li>Another not-so-apparent problem is that we’re using the inbuilt List endpoint to return a single user’s information, not a list.</li></ul><p>The solution to tackle these problems is to use a <strong>custom endpoint. </strong>Let’s call this endpoint the me endpoint.It always returns information about the current user.</p><h3>Custom Endpoints:</h3><ol><li>We first define a function called me inside the UserViewSet class. <strong>By naming the function me, our endpoint’s </strong><strong>URL will also become </strong><strong>www.hostname.com/users/me</strong>. We will pass two arguments to me: self and request. If you’ve gotten this far, I’m sure you’re familiar with these arguments.</li></ol><pre>def me(self, request):<br>    pass</pre><p>2. We will then get the serializer from self.</p><pre>def me(self, request):<br>    serializer = self.get_serializer_class()</pre><p>3. Then we get the serialized data for the current user and return that as a response.</p><pre>def me(self, request):<br>    serializer = self.get_serializer_class()<br>    data = serializer(request.user).data<br>    return Response(data, status=status.HTTP_200_OK)</pre><blockquote><strong><em>Pro Tip</em></strong><em>: Avoid using numbers when setting the status codes. Always use the inbuilt status codes that Django Rest Framework provides. This makes your code scalable in case (very unlikely) the status codes are changed. i.e.-</em></blockquote><blockquote>return Response(data, status=200) — — — Wrong</blockquote><blockquote>return Response(data, status=status.HTTP_200_OK) — — — Correct</blockquote><blockquote><a href="https://www.django-rest-framework.org/api-guide/status-codes/"><strong><em>Here</em></strong></a><em> is a list of DRF’s status codes for your reference.</em></blockquote><p>4. The last step is to use the action decorator. If you are not familiar with what a decorator is:</p><blockquote>decorators are a tool in Python that allow programmers to modify the behavior of an existing function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.</blockquote><blockquote>Essentially, a decorator is a piece of code (A) that changes the behavior of another piece of code (B) without actually changing the code (B) itself. When this happens, we say that the we are wrapping a piece of code (B) with a decorator (A).</blockquote><p><a href="https://www.geeksforgeeks.org/decorators-in-python/">This</a> is an excellent resource to learn more about decorators.</p><p>The action decorator wraps the function we just made. It converts the normal python function into an endpoint. <strong>Here is the syntax:</strong></p><p>@action(methods=[&#39;get&#39;, &#39;post&#39;, &#39;patch&#39;], detail=True, permission_classes=[IsAuthenticated. IsAdmin])</p><p>Let’s break it down,</p><ul><li>methods : These are the HTTP request types that the endpoint accepts.</li><li>detail : This option decides whether the endpoint is a detail view or a general view. A detail view usually contains the primary key of an object in the URL. For example: api.domain.com/users/3/ is a detail view of the user with user_id=3.</li><li>permission_classes : This is similar to the parent class’ permission_classes option. This allows you to set custom permissions per endpoint if you want. You can omit this option to inherit the parent class’ permissions.</li></ul><blockquote><strong><em>Pro Tip</em></strong><em>: If you decide to set custom permission classes per endpoint, remember that </em><strong><em>the parent class’ permissions don’t get added to the permissions you add.</em></strong><em> Essentially:</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sdEung_uTIRSV2qPdL-hA.png" /></figure><p>Finally, let’s see how the code looks after adding this new endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e5bb2768ccedfbb8ccbebbb1a5c5e64/href">https://medium.com/media/1e5bb2768ccedfbb8ccbebbb1a5c5e64/href</a></iframe><p>Here’s the breakdown:</p><ul><li>We got rid of the ListModelMixin, we don’t need that anymore.</li><li>We changed the get_queryset to return all the users now, because we aren’t even using the queryset in the me endpoint anymore. In the future however, there may be endpoints in this ViewSet that do need the queryset, so we will set it up for the future.</li><li>We added a new function who’s structure we already discussed. But we also added our decorator: <br>- We are only allowing the get method for now.<br>- It’s not a detail endpoint, it will always only return the current user’s info.<br>- We are not overriding the parent class’ permissions.</li></ul><p>And here we are. We have a functional, clean, and optimum view to retrieve the current user’s profile information. Let’s have a look at it’s response before we wrap things up.</p><p>To get a response, we need to connect a URL to our Generic ViewSet. Because our focus is the ViewSet, we will use a shorter way to create the URL. We will explore the optimum way of managing URLs in a later series. (Just in case you’re curious, we should use routers, you can find more about them here).</p><p>Add the URL in the urls.py of the main app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3963d5e8767be684e259325eefc79c24/href">https://medium.com/media/3963d5e8767be684e259325eefc79c24/href</a></iframe><p>On calling the http://localhost:8000/users/me endpoint, this is the response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*qhUxVfa0jgrYfgBJvcU1cQ.png" /></figure><p><strong>Fantastic!</strong> Hopefully, this is enough information for you to start making custom endpoints for any purpose you need. We have covered a lot in this article. Go through it as many times as you need, if you face any issues, you can leave a comment here and I’ll do my best to help you out.</p><p>Well, we can wrap it up here. We haven’t dealt with multiple serializers, multiple querysets, custom mixins and such yet, but we will very soon.</p><p>Stay tuned and I’ll see you soon.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12XDYvMJNcmLgQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12XDYvMJNcmLgQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F12XDYvMJNcmLgQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="325" frameborder="0" scrolling="no"><a href="https://medium.com/media/3036ebf1372b812578b622f81b6c5de0/href">https://medium.com/media/3036ebf1372b812578b622f81b6c5de0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e746210173f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-custom-endpoints-5e746210173f">Generic ViewSets — Custom Endpoints</a> was originally published in <a href="https://medium.com/django-rest-for-not-beginners">Django Rest for Not Beginners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generic ViewSets — An Introduction]]></title>
            <link>https://medium.com/django-rest-for-not-beginners/generic-viewsets-an-introduction-be8712a37e6d?source=rss-5550363417b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/be8712a37e6d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Caronex Labs]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 17:49:55 GMT</pubDate>
            <atom:updated>2020-07-05T17:49:55.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generic ViewSets — An Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1O54viUBB0hLFek-lAmQg.png" /></figure><p>Glad to have you onboard! This is the starting line. An introduction to Generic ViewSets, their uses and how to customize them to fit your needs.</p><p>I believe the best place to start is to see where we need to end up. And we have a very simple aim... we need to build this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pOID_f8_fUE92CMo_I8Dg.jpeg" /><figcaption>The Medium Profile Page… with a few additions.</figcaption></figure><p>For those of you who just went to their profile pages to see the article count, welcome back. For those who didn’t, please have a good look at the above image… we’re going to be staring at it quite a bit throughout this series.</p><p>Like I promised in the <a href="https://medium.com/django-rest-for-not-beginners/prologue-f6a35ba42193"><strong>Prologue</strong></a><strong>, </strong>here are a <strong>list of things you should be familiar with:</strong></p><ul><li><a href="https://docs.djangoproject.com/en/3.0/topics/db/models/">Django Models</a> — How to build them.</li><li><a href="https://www.django-rest-framework.org/api-guide/serializers/">Serializers</a> — Model Serializers</li><li><a href="https://docs.djangoproject.com/en/3.0/topics/auth/customizing/">AbstractUser</a> — And how to set them up. (I will go over this as well.)</li><li><a href="https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset">ModelViewSets</a> — Are awesome.</li></ul><h3><strong>Setting The Project Up</strong></h3><p><em>…The author then set the project up…</em></p><p>Here is the directory structure to make you feel a little comfortable…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*hPHQe0yS_EZaWMskjvKYJw.png" /></figure><p>We will be working primarily with the users_module directory. You can find this project <a href="https://github.com/Caronex-Labs/DjangoRestForNotBeginners/tree/master/_1_GenericViewSets"><strong>here</strong></a>.</p><p>Let’s start with the models. We will only consider the User model for now. Let’s deal with the articles themselves a little later.</p><pre><strong>An aside on the AbstractUser:</strong></pre><pre>Traditionally, if we wanted the User of our system to have more fields (in our case we have the bio, the headline etc). We would make a model, usually called `profile` and then have a one-to-one relation with the user model. </pre><pre>However, <strong>the recommended way now is to use AbstractUser</strong>. AbstractUser is a way for you to extend your User model without completely overwriting the inbuilt Django User model. As you can see below, we inherit the AbstractUser and we don&#39;t need the `models.Model`. I have mentioned it in the comments below as well, that the first 5 fields do not need to be mentioned, they will be there even if we don&#39;t write them explicitly.</pre><pre>For more information, I highly recommend this article by <em>Vitor Freitas - </em><a href="https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html"><em>Simple Is Better Than Complex: How To Extend The Django User Model</em></a></pre><p>Here is the User model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03609f79d77a78b36643973594f9c49e/href">https://medium.com/media/03609f79d77a78b36643973594f9c49e/href</a></iframe><p>Now, there are a few things that should strike you as problematic:</p><ul><li>We would never store articles or following this way. They are both dynamic properties and should be calculated in the serializer, the view or by using a computed property (We will talk about this in a future series).</li><li>The headline is dynamic as well and should be calculated in a view.</li><li>The bio should have a max length.</li></ul><p>We will fix these issues eventually, but they are actually going to force us to use the topics we discuss in this series.</p><p>Let’s talk about the views now. <strong>We will assume that we only want to retrieve information for now. </strong>Here is the way we would do it using ModelViewSet :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d0d21358cd0d3a1b79400f6f9cfaa83/href">https://medium.com/media/1d0d21358cd0d3a1b79400f6f9cfaa83/href</a></iframe><p>The serializer is simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a8b35afa6b7aa1c085409294ae6013a/href">https://medium.com/media/4a8b35afa6b7aa1c085409294ae6013a/href</a></iframe><p>This is ugly. There is redundancy in the code, we are repeating ourselves multiple times, and I’m confident my editor thinks I’m stupid.</p><p>Many of you will very rightly point out that <strong>ModelViewSets were not meant for a single endpoint</strong>. They are meant to make it easier to build multiple endpoints that pertain to the same model. But scalability is something a developer should always keep in mind, your code should be future proof. In our case, we will be adding more endpoints in the future.</p><p>Here is the Generic ViewSet doing the same thing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2d5b7e774ab9b466d66707dc9b114c/href">https://medium.com/media/cd2d5b7e774ab9b466d66707dc9b114c/href</a></iframe><p><strong>The only change you will notice is the </strong><strong>ListModelMixin. </strong>We have inherited a class ListModelMixin in our original UserViewSet.</p><p>A mixin is basic python class inheritance. When I include the ListModelMixin, there is a piece of code that is included in the current class without me having to explicitly write it.</p><p>Here is the code if you wanna have a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*eOshHSFlvEYjE49lBuCH4A.png" /></figure><p>This is the same list endpoint that is auto created when you use ModelViewSet.</p><p>So basically, you can now choose which endpoints you want and which ones are not relevant. Similar to this, there are:</p><ul><li>CreateModelMixin</li><li>UpdateModelMixin</li><li>RetrieveModelMixin</li><li>DestroyModelMixin</li></ul><blockquote><strong>Pro Tip:</strong> Your view won&#39;t work if the <em>mixins</em> are not the first to be inherited.</blockquote><blockquote>class UserViewSet(GenericViewSet, ListModelMixin) --- Wrong</blockquote><blockquote>class UserViewSet(ListModelMixin, GenericViewSet) --- Correct</blockquote><p>We have not yet dealt with the get_queryset() issue. The fact that we’re using a get_queryset method that only returns a single User object. But that’s also a set-up for a future article.</p><p>Essentially,</p><blockquote>Generic ViewSets are bare-bone versions of Model ViewSets. They don’t come with the out of the box implemented endpoints. They do however, come with the get_queryset and the get_serializer_class methods.</blockquote><p>Well, that’s it for this one. We set the project up and explored the basic difference between GenericViewSets and ModelViewSets. In the upcoming articles however, things get a little more interesting when we talk about custom endpoints.</p><p>I hope to see you soon…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYnGDmAudv7F2UASBqK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYnGDmAudv7F2UASBqK%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FYnGDmAudv7F2UASBqK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e36aa40a8dd995cab3927247e82601a/href">https://medium.com/media/3e36aa40a8dd995cab3927247e82601a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be8712a37e6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-rest-for-not-beginners/generic-viewsets-an-introduction-be8712a37e6d">Generic ViewSets — An Introduction</a> was originally published in <a href="https://medium.com/django-rest-for-not-beginners">Django Rest for Not Beginners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prologue]]></title>
            <link>https://medium.com/django-rest-for-not-beginners/prologue-f6a35ba42193?source=rss-5550363417b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6a35ba42193</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Caronex Labs]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 10:19:08 GMT</pubDate>
            <atom:updated>2020-07-04T16:23:25.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGL2hNVPWteKylOQgOo8kw.png" /></figure><p>Every developer seems to go through a few distinct phases in his or her journey of firstly learning and then implementing.</p><p>When I first started learning Django, there was… too much information. I couldn’t run out of resources to learn from and I’d hear something new in every article I read or tutorial I watched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*ZTqws-KifCHyV7ncGj2vlg.gif" /><figcaption>Historically Accurate Depiction Of Me Learning Django</figcaption></figure><p>That changed though, I hit the ceiling of what I could learn by watching other people or reading about their experiences. I was at a point where I had to make my own experiences and learn from those instead. Which may not be such a bad thing… except for the fact that the thought of <strong><em>Studying Documentation</em></strong> frightens me.</p><p>Documentation is perfect for when you want something to happen and you just want to know how to make it happen. But what do you do when you <strong>don’t even know what you want</strong>. That is my drive behind this series.</p><p>This series of articles will revolve around aspects of the Django Rest Framework that are <strong>NOT</strong> taught in tutorials. Things that you are expected to learn on your own… without even knowing that they exist.</p><p>My aim with this publication is to build a bridge between where those tutorials leave you, and where the industry expects you to be.</p><p>Here’s a quick rundown of what I hope to cover:</p><ol><li>GenericViewSets — The top of your toolbox.</li><li>Routers — DRF can handle your endpoints.</li><li>Serializers — Beyond the Basics.</li><li>Permissions and Groups — Handling Hierarchy.</li><li>Caching and Throttling — Moderating API Interactions.</li><li>Documentation — Is not that painful.</li></ol><p>Each of the above subtopics will have a few articles under them but we will not cover the basics. I will mention the topics I assume you are familiar with at the beginning of each article.</p><p>I will put up links to the documentation in each article, because <strong>this series is not an alternative to the docs</strong>. It’s a window that tells you what exists and a little bit of how to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Jn6cePVB53Pvz-raQEpZYQ.gif" /></figure><p>Let’s get to that bridge.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6a35ba42193" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-rest-for-not-beginners/prologue-f6a35ba42193">Prologue</a> was originally published in <a href="https://medium.com/django-rest-for-not-beginners">Django Rest for Not Beginners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>