Issue
I have Progress model which relates with Deck model by OneToOne relation. I want to get Progress object from API by passing deck_id to 'http://localhost/api/v1/progress/deck_id/' endpoint. How I can do this? Or may be should I consider other implementations of retrieving Progress object? Also I want all CRUD functions with this model.
class Deck(models.Model):
name = models.CharField(max_length=70)
owner = models.ForeignKey(
CustomUser,
on_delete=models.CASCADE,
related_name='decks',
)
class Progress(models.Model):
deck = models.OneToOneField(Deck)
progress = models.JSONField(
null=True
)
class ProgressViewSet(viewsets.ModelViewSet):
queryset = Progress.objects.all()
serializer_class = ProgressSerializer
permission_classes = (OwnerOrAdminProgress,)
lookup_field = 'id'
http_method_names = ['get', 'post', 'patch', 'delete']
class ProgressSerializer(serializers.ModelSerializer):
progress = serializers.JSONField()
class Meta:
model = Progress
fields = ('id', 'deck', 'progress')
router_v1 = routers.DefaultRouter()
router_v1.register('v1/decks', DeckViewSet, basename='decks')
router_v1.register('v1/progress', ProgressViewSet, basename='progress')
urlpatterns = [
path('', include(router_v1.urls)),
]
Solution
We can add action to ProgressViewSet:
@action(
detail=False,
permission_classes=[OwnerOrAdminProgressDeck],
methods=['get'],
url_path='deck/(?P<deck_id>[^/.]+)'
)
def progress_by_deck(self, request, deck_id=None):
try:
deck = Deck.objects.get(id=deck_id)
progress = Progress.objects.get(deck=deck)
serializer = ProgressSerializer(progress)
return Response(serializer.data)
except (Deck.DoesNotExist, Progress.DoesNotExist):
return Response(
{"error": "Progress not found for the given deck_id"},
status=status.HTTP_404_NOT_FOUND,
)
Answered By - CarloDiPalma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.