Casting objects in django model

后端 未结 2 1359
青春惊慌失措
青春惊慌失措 2021-01-25 14:25

I am making a django project with models.py having following code:

class Record(models.Model):
    id = models.AutoField(primary_key=True)

class TTAMRecord(Reco         


        
相关标签:
2条回答
  • 2021-01-25 14:48

    If I understood your concept of "cast" it will not work in the way you described.

    However, to get model inheritance to work you need to use abstract models (see docs)

    class Record(models.Model):
        # Some generic fields
        class Meta:
            abstract = True
    
    class TTAMRecord(Record):
        client = models.ForeignKey(TTAMClient)
    

    If you need both Record and TTAMRecord to be stored in Account you will need to use polymorphic relationships, that in Django it's called Generic Relations (see docs)

    You will need an intermediary model to store these generic relations. So, basically you will have a AccountRecord and a Account model:

    class AccountRecord(models.Model):
        content_type = models.ForeignKey(ContentType)
        object_id = models.PositiveIntegerField()
        content_object = generic.GenericForeignKey('content_type', 'object_id')
    
    class Account(models.Model):
        records = models.ManyToManyField(AccountRecord)
    

    And so you can do:

    account = Account.objects.get(...)
    for record in account.records.all():
        record_content = record.content_object
        if isinstance(record_content, TTAMRecord):
            client = record_content.client
        else:
            # No client available
    
    0 讨论(0)
  • 2021-01-25 14:50

    As Record is not abstract model, it has its own table and life cycle as other models. However, you can access the corresponding client object as record.ttamclient, so you can change your line to

    account = Account.objects.get(...)
    for record in account.records.all():
        client = record.ttamclient
        ...
    

    However, this is little cumbersome if you have multiple derived classes. In such cases you would have to know which derived class you are referring to and use the corresponding attribute name.

    0 讨论(0)
提交回复
热议问题