Search code examples
pythonjsondjangoserializationdjango-taggit

losing subclass fields when serializing in django?


I see baffling and what seems flatout bad behavior in serializing django objects. For example, I have models:

class MyTag(TagBase):
    user = models.ForeignKey(User)


class MyMpttTag(MPTTModel, MyTag):
    parent      = TreeForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        parent_attr         = 'parent'

which means that MyMpptTag has fields of name, slug, user, parent. But when I do serializers.serialize('json', MyMpptTag.object.all()), I get: [{"fields": {"lft": 1, "level": 0, "tree_id": 29, "parent": null, "rght": 2}, "model": "index.mymptttag", "pk": 45}...]

Why would I lose name, slug, and user, and how do I get them back? Thank you


Solution

  • On that model design, you will have 2 tables in database:

    • yourapp_mytag that will have primary key column (normal auto-increment column), all columns inherited from TagBase (as long as TagBase is abstract) and column user - foreign key to model User
    • yourapp_mymptttag tht will have primary key column that is also foreign key to MyTag model and columns for mptt. There won't be any columns inherited from MyTag.

    That means: there are no columns inherited from MyTag in model MyMpttTag, there are only references to actual columns in MyTag.

    In serialization there will be 2 type of objects: MyMpttTag and MyTag.