Help... Serializer by name

Hi,

I want to reference a serializer by name. Is this possible?

For example:
data = get_serializer(‘serializerName’, modelName.objects.all())

I have done a lot of googling but can’t find anything.

Thanks in advance.
Jade

Why are you trying to get a serializer by name?
Is this going to be dynamic defined by user input?

A form will dynamicly change based on user input.

And I ideally don’t want to hardcore each serializer, I want to handle it more gracefully by name.

I recently answered a similar question here, the only difference is that the other person was trying to instance a form. But you can take that as a start. Please be aware of the latest comments on that thread, since this can lead to security issues.

Since the serializer is a class, you have access to it just like any other class. So yes, you can set something up to reference serializers by a name. My general recommendation for situations like this is to create your own dict associating names with classes, and then create an instance of the desired class by referencing it from the dict. That’s a lot more safe than trying to dynamically import classes based upon indeterminate factors.

Hi,

Thanks that sounds awesome. I’m newish to django and python.

Can you give me an example or simular example so I can investigate?

Thanks
Jade

Something like this:

def some_view(request):
    serializer_type = "customer" # or from other source like request.GET or request.data
    serializers = {"customer": CustomerSerializer, "vendor": VendorSerializer}
    SerializerClass = serializers[serializer_type]  # will raise key error if not found
    srlzr = SerializerClass(request.data)

Thanks I will give that a crack :slight_smile: