Summary: Why shouldn't I put model, serializer and view classes for the same object in the same file in my Django Rest Framework application?
I'm building an application using the Django Rest Framework, which I'm relatively new to. I've had some exposure to Ruby on Rails so I'm familiar with the MVC idiom and its logic, and the separation of files made more sense there since the view was an HTML file with some embedded Ruby.
I am finding it a little inefficient jumping between models.py, serializers.py and views.py when adding new objects or making changes to existing ones. It feels like it would be easier to have a file per object (or group of closely related objects) with model, serializer and view classes all near each other.
For a trivial example, why do this:
# models.py from django.db import models class Thing(models.Model): name = models.CharField() # serializers.py from rest_framework import serializers from models import Thing class ThingSerializer(serializers.ModelSerializer): class Meta: model = Thing fields = ['id', 'name'] # views.py from rest_framework import generics from models import Thing from serializers import ThingSerializer class ThingList(generics.ListCreateAPIView): queryset = Thing.objects.all() serializer_class = ThingSerializer when you could do this:
# thing.py from django.db import models from rest_framework import serializers, generics class Thing(models.Model): name = models.CharField() class ThingSerializer(serializers.ModelSerializer): class Meta: model = Thing fields = ['id', 'name'] class ThingList(generics.ListCreateAPIView): queryset = Thing.objects.all() serializer_class = ThingSerializer I'm sure this is something that people have thought about and come up with good reasons to structure a project this way, but searching on Google, StackOverflow and here I haven't managed to find anything.