title: Django Rest Framework - Updating a ForeignKey Field entry in the view
body: <p>In my <code>Django Rest Framework</code> project, I have a <code>ForeignKey</code> relationship between two models:</p>
  <pre><code>class Book(models.Model):
      ...
      category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
      ...
  
  class Category(models.Model):
          name = models.CharField(max_length=100, blank=False)
  </code></pre>
  <p>As you can see, a <code>Book</code> <em>can</em> belong to a <code>Category</code> but <em>it does not have to</em>. That means the '<code>category</code>' field could be null.
  So, in my <code>views.py</code>, any <code>Book</code> instance can be updated/patched if the user wants to assign a certain <code>Book</code> to a particular <code>Category</code>. That <code>views.py</code> update method looks like this:</p>
  <pre><code>class UpdateBooksCategory(generics.GenericAPIView):
      '''
          Class-based view to update the 'category' field of a Book instance.
      '''
      serializer_class = BookSerializer
      permission_classes = [IsAuthenticated]
  
      def patch(self, request,*args, **kwargs):
          # get the Book instance first
          book = Book.objects.get(pk=request.data.get('bookId'))
  
          # if it is not assigned to a Category, then assign it
          if book and not book.category:
              book.category = Category.objects.get(name=request.data.get('categoryName'))
              book.save()
  
              serializer = self.get_serializer(book, context={&quot;request&quot;: request})
      
              return Response(serializer.data)
              
          # otherwise, return a generic response
          return Response({'response': &quot;You have already put the selected Book in a Category.&quot;})
  </code></pre>
  <p>If you can see, first I get the <code>Book</code> instance that the user wants to update by using the <code>Book</code>'s ID. If its <code>Category</code> field is not already filled, I get a <code>Category</code> instance using the given category name and assign it.</p>
  <p>For the sake of completeness, here are my serializer classes:</p>
  <pre><code>class CategorySerializer(serializers.ModelSerializer):
      class Meta:
          model = Category
          fields = ['id', 'name']
  
  
  class BookSerializer(serializers.ModelSerializer):
      class Meta:
          model = Book
          fields = ['id', /*some other fields*/,..., 'category']
  </code></pre>
  <p>So, finally my question: I wanted to know if this is the preferred way of updating a <code>ForeingKey</code> field like this? I mean looking at the <code>UpdateBooksCategory</code> class-based view, is this the right way of doing it? The code works ( I tested it with PostMan) but since I am new to DRF I wanted to know if such an updating process is correct.</p>