[Django]-Django – serialize polymorphic model

3πŸ‘

βœ…

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")
πŸ‘€Anentropic

Leave a comment