ModelSerializerFactory?

28 views
Skip to first unread message

litewaitt

unread,
Feb 20, 2015, 1:50:11 PM2/20/15
to django-res...@googlegroups.com
With the advent of DRF 3 (unless I am missing something), all classes that inherit from ModelSerializer will not work if I was leaning on the "model" attribute in the class to do the work of setting the query_set and serializer_class for me.

My thought is to replace the line:

model = MyModel

with:

query_set = MyModel.objects.all()
serializer_class = ModelSerializerFactory(MyModel)

The goal here is to remove the need to create the boilerplate serializers for the models and just generate them dynamically. Is that a workable solution, or is there a better way?

Not really sure how to create a ModelSerializer dynamically, since I am new to Python, but it seems to be a solution.

Tom Christie

unread,
Feb 20, 2015, 3:45:25 PM2/20/15
to django-res...@googlegroups.com
You could, yes. Here's how `ModelSerializerFactory` would look if you wanted to do that:

def ModelSerializerFactory(model_class):
    class DynamicSerializer(ModelSerializer):
        class Meta:
            model = model_class
    return DynamicSerializer

litewaitt

unread,
Feb 24, 2015, 10:02:25 AM2/24/15
to django-res...@googlegroups.com
Tom,
Thanks that worked perfectly.
Reply all
Reply to author
Forward
0 new messages