Skip to content

Commit

Permalink
fix(generic): use serializer_factory even with custom serializers
Browse files Browse the repository at this point in the history
This allows projects to use custom generic serializers that do not have
a `Meta.model` set.
  • Loading branch information
b1rger committed Feb 29, 2024
1 parent b021696 commit edb3990
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
11 changes: 6 additions & 5 deletions apis_core/generic/api_views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from rest_framework import viewsets
from .serializers import serializer_factory
from .serializers import serializer_factory, GenericHyperlinkedModelSerializer
from .helpers import first_match_via_mro


Expand All @@ -23,7 +23,8 @@ def get_queryset(self):
return queryset or self.model.objects.all()

def get_serializer_class(self):
serializer_class = first_match_via_mro(
self.model, path="serializers", suffix="Serializer"
) or serializer_factory(self.model)
return serializer_class
serializer_class = (
first_match_via_mro(self.model, path="serializers", suffix="Serializer")
or GenericHyperlinkedModelSerializer
)
return serializer_factory(self.model, serializer=serializer_class)
4 changes: 3 additions & 1 deletion apis_core/generic/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ class GenericHyperlinkedModelSerializer(HyperlinkedModelSerializer):
def serializer_factory(
model, serializer=GenericHyperlinkedModelSerializer, fields="__all__", **kwargs
):
meta = type(str("Meta"), (object,), {"model": model, "fields": fields})
defaultmeta = type(str("Meta"), (object,), {"fields": fields})
meta = getattr(serializer, "Meta", defaultmeta)
meta.model = model
serializer = type(
str("%sModelSerializer" % model._meta.object_name),
(serializer,),
Expand Down

0 comments on commit edb3990

Please sign in to comment.