Houman
Houman

Reputation: 66320

Django: How to save inherited models?

class Conversation(models.Model):
    contact             = models.ForeignKey(Contact)
    conversation_datetime = models.DateTimeField()    
    notes               = models.TextField(_(u'Notes'),        blank=True)    

    def __unicode__(self):
        return self.conversation_datetime


class Conversation_history(Conversation):
    log_date_time = CreationDateTimeField()
    def __unicode__(self):
        return self.conversation_datetime

Not sure if this is the best to do it, but I was hoping to create a history table of each major mode, so that I can follow what the customer was doing and help them in a support case.

I have created a new model based on the original model. But when I save an instance of the new model, the original table gets populated. I have no idea why.

call = Conversation(contact='', conversation_datetime = '', notes='')
call.save()

ch = Conversation_history(contact='', conversation_datetime = '', notes='')
ch.save()

Upvotes: 0

Views: 165

Answers (1)

Aidan Ewen
Aidan Ewen

Reputation: 13308

Because you haven't declared your Conversation model to be abstract. You're using multi-table inheritance. Have a look at the docs.

If you want all the data stored in your child then you should do something like -

class ConversationBase(models.Model):
    contact             = models.ForeignKey(Contact)
    conversation_datetime = models.DateTimeField()    
    notes               = models.TextField(_(u'Notes'),        blank=True)  

    class Meta:
        absract = True

class Conversation(ConversationBase):
    pass

class ConversationHistory(ConversationBase):
    log_date_time = CreationDateTimeField()

Upvotes: 1

Related Questions