Below the Radar
Below the Radar

Reputation: 7635

Django - serialize polymorphic model

I would like to serialize a polymorphic model but only his base type fields are serialized, not those of the polymorphic.

models.py

class Folder(PolymorphicMPTTModel):
    parent = PolymorphicTreeForeignKey('self', null=True, blank=True, related_name='children')
    name = models.CharField(max_length=50)

class File(Folder):
    srs_wkt = models.CharField(max_length=1000, blank=True, null=True)

views.py

from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder

file = File.objects.get(pk=1)
serialized = serializers.serialize('python', [file,])
response = json.dumps({'file':file}, cls=DjanJSONEncode)
return HttpResponse(response, content_type="application/json")

That's how I usually do to serialize my model object and send it as JSON, but here, the JSON object has only the srs_wkt field, not the name.

Is there a way to serialize polymorphic model?

Upvotes: 3

Views: 1342

Answers (1)

Anentropic
Anentropic

Reputation: 33833

the reason is that Folder is not an abstract model, so you have:
https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance

in most places Django hides the underlying OneToOneField that binds the two models together, but the serializer does not, see here:
https://docs.djangoproject.com/en/dev/topics/serialization/#inherited-models

They provide in the docs above a recipe for your situation, but it's not very elegant so I'd suggest trying an alternative such as:

from django.core.serializers.json import DjangoJSONEncoder

def myview(request):
    file_dict = File.objects.filter(pk=1).values()[0]
    folder_dict = Folder.objects.filter(pk=file.folder.pk).values()[0]
    folder_dict.update(file_dict)
    response = json.dumps({'file': folder_dict}, cls=DjangoJSONEncoder)
    return HttpResponse(response, content_type="application/json")

Upvotes: 3

Related Questions