Make sure you don't push DB files (files with .sqlite
, .db3
, etc. extension).
Make sure you don't push .pyc
, .idea
files.
- Avoid using an
if
condition to check if a serializer is valid. Instead, use theraise_exception=True
flag when callingserializer.is_valid()
. This will automatically raise aValidationError
if the data is invalid, which is then caught by the DRF exception handler to return a400 Bad Request
response.
Good example:
if request.method == 'POST':
serializer = MovieSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
Bad example:
if request.method == 'POST':
serializer = MovieSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
- Make sure that your
Response
returns status code:
Good example:
if request.method == "GET":
serializer = MovieSerializer(movie)
return Response(serializer.data, status=status.HTTP_200_OK)
Bad example:
if request.method == "GET":
serializer = MovieSerializer(movie)
return Response(serializer.data)
- If you specify
max_length
then it's more reasonable to useCharField
instead ofTextField
:
Good example:
class Book(models.Model):
description = models.CharField(max_length=255)
Bad example:
class Book(models.Model):
description = models.TextField(max_length=255)
- Make sure that all your endpoints end with
/
:
Good example:
urlpatterns = [
path("movies/<pk>/", movie_detail, name="movie-detailed")
]
Bad example:
urlpatterns = [
path("movies/<pk>", movie_detail, name="movie-detailed")
]
-
Make sure you catch an error in
@api_view
in case that object doesn't exist. Useget_object_or_404
instead oftry
/except
for this purpose. -
Make sure you've added a blank line at the end of all your files.
-
A serializer field is required by default. (DRF required documentation)
-
Your project should be one-styled, don't use double and single quotes at the same time. Double quotes are preferred.
Add comments, prints, and functions to check your solution when you write your code. Don't forget to delete them when you are ready to commit and push your code.