Added a custom user serializer to allow sorting of notes by user

This commit is contained in:
keannu125 2023-03-01 23:27:46 +08:00
parent 65ad4a5f21
commit ff7934407a
5 changed files with 23 additions and 2 deletions

View file

@ -0,0 +1,12 @@
from django.contrib.auth.models import User
from rest_framework import serializers
from notes.models import Note
class CustomUserSerializer(serializers.ModelSerializer):
notes = serializers.PrimaryKeyRelatedField(
many=True, queryset=Note.objects.all())
class Meta:
model = User
fields = ['id', 'username', 'notes']

View file

@ -41,7 +41,8 @@ INSTALLED_APPS = [
'rest_framework.authtoken',
'notes.apps.NotesConfig',
'corsheaders',
'djoser'
'djoser',
'accounts',
]
MIDDLEWARE = [
@ -146,6 +147,9 @@ DJOSER = {
'SEND_ACTIVATION_EMAIL': True,
'SEND_CONFIRMATION_EMAIL': True,
'ACTIVATION_URL': 'activation/{uid}/{token}',
'SERIALIZERS': {
'user': 'accounts.serializers.CustomUserSerializer'
},
}
EMAIL_HOST = 'sandbox.smtp.mailtrap.io'

Binary file not shown.

View file

@ -3,6 +3,8 @@ from .models import Note
class NoteSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Note
fields = ('id', 'title', 'content', 'date_created')
fields = ('id', 'title', 'content', 'date_created', 'owner')

View file

@ -13,3 +13,6 @@ class NoteViewSet(viewsets.ModelViewSet):
user = self.request.user
queryset = Note.objects.filter(owner=user).order_by('date_created')
return queryset
def perform_create(self, serializer):
serializer.save(owner=self.request.user)