简体   繁体   中英

multiple model object inheritance in django

In django, I have three models:

class Base(models.Model):
    pass

class ChildA(Base):
    pass

class ChildB(Base):
    pass

I'm using MySQL, so after syncdb , I have three table:

tb_base , tb_childa and tb_childb , which the primary of both tb_childa and tb_childb are also foreign key of the primary key of tb_base .

Structurally speaking, I can have objects of Model Base , ChildA and ChildB having the same id.

For example, now I execute:

childa = ChildA.objects.create()
print(childa.pk) # printed: 1

The above code added one row in tb_base and tb_childa , both with primary key id to be 1.

Now I want to create a ChildB instance, but it shares the base object of childa .

For example:

# this doesn't work, but shows what I want to do. 
childb = ChildB.objects.create(base=Base.objects.get(pk=1))

My final purpose is to use ChildA and ChildB Models in different cases, but if it's base part fields updated, they can share it.

Also, I want to consider the behavior when the objects be deleted.

I don't see much sense in this, but you can do:

childb = ChildB.objects.create(base_ptr_id=1))

You might consider to define another class which holds shared data between ChildA and ChildB.

from django.db import models


class SharedData(models.Model):
    data = models.CharField("Data", max_length=50)


class Base(models.Model):
    shared_data = models.ForeignKey(SharedData)


class ChildA(Base):
    pass


class ChildB(Base):
    pass

You can try like this:

child_b = Base.objects.get(pk=1)
child_b.__class__= ChildB
child_b.save()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM