hyperlinked relations

This commit is contained in:
Pratyush Desai 2022-01-08 06:56:58 +05:30
parent d2909e5ce9
commit f0975c6505
Signed by: pratyush
GPG Key ID: DBA5BB7505946FAD
2 changed files with 19 additions and 8 deletions

View File

@ -3,15 +3,16 @@ from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.ModelSerializer):
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
class Meta:
model = Snippet
fields = ['id', 'title', 'owner', 'code', 'linenos', 'language', 'style']
fields = ['url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style']
class UserSerializer(serializers.ModelSerializer):
snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
class Meta:
model = User
fields = ['id', 'username', 'snippets']
fields = ['url', 'id', 'username', 'snippets']

View File

@ -4,11 +4,21 @@ from . import views
urlpatterns = [
path('', views.api_root),
path('snippets/', views.SnippetList.as_view()),
path('snippets/<int:pk>/', views.SnippetDetail.as_view()),
path('users/', views.UserList.as_view()),
path('users/<int:pk>/', views.UserDetail.as_view()),
path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view()),
path('snippets/',
views.SnippetList.as_view(),
name='snippet-list'),
path('snippets/<int:pk>/',
views.SnippetDetail.as_view(),
name='snippet-detail'),
path('snippets/<int:pk>/highlight/',
views.SnippetHighlight.as_view(),
name='snippet-highlight'),
path('users/',
views.UserList.as_view(),
name='user-list'),
path('users/<int:pk>/', views.UserDetail.as_view(),
name='user-detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns)