Casting objects in django model

后端 未结 2 1388
青春惊慌失措
青春惊慌失措 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
    

提交回复
热议问题