Ehtasham Ali
Ehtasham Ali

Reputation: 3

Refer to child class foreign key in base abstract model

I am trying to access the child model foreign key in base abstract model so I don't have to repeat the foreign key in each of the child model.

Here is my code:

class BaseModel(models.Model):
    child_field = models.ForeignKey(to='child_class_either_ModelA_OR_ModelB')

    class Meta:
        abstract = True


class ModelA(BaseModel):
    ....

class ModelB(BaseModel):
    ....

I want to refer the child model in base abstract model.

Is there a way to use an child model in base model?

Upvotes: 0

Views: 619

Answers (1)

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10699

As the fields in the abstract BaseModel would be inherited, then we could have ModelA.child_field that references itself (ModelA) and ModelB.child_field that references itself (ModelB) by declaring a ForeignKey that references itself as documented here:

To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).

class BaseModel(models.Model):
    child_field = models.ForeignKey(to='self', on_delete=models.CASCADE, null=True)

    class Meta:
        abstract = True


class ModelA(BaseModel):
    field_a = models.CharField(max_length=200)


class ModelB(BaseModel):
    field_b = models.CharField(max_length=200)
>>> from my_app.models import *
>>> 
>>> model_a_1 = ModelA.objects.create(field_a="Value 1")
>>> model_a_2 = ModelA.objects.create(field_a="Value 2", child_field=model_a_1)
>>> ModelA.objects.values()
<QuerySet [{'id': 1, 'child_field_id': None, 'field_a': 'Value 1'}, {'id': 2, 'child_field_id': 1, 'field_a': 'Value 2'}]>
>>> 
>>> model_b_3 = ModelB.objects.create(field_b="Value 3")
>>> model_b_4 = ModelB.objects.create(field_b="Value 4", child_field=model_b_3)
>>> ModelB.objects.values()
<QuerySet [{'id': 1, 'child_field_id': None, 'field_b': 'Value 3'}, {'id': 2, 'child_field_id': 1, 'field_b': 'Value 4'}]>

Cross-references in between different child models would fail e.g. ModelA linked to ModelB.

>>> model_a_5 = ModelA.objects.create(field_a="Value 5", child_field=model_b_4)
Traceback (most recent call last):
    raise ValueError(
ValueError: Cannot assign "<ModelB: ModelB object (2)>": "ModelA.child_field" must be a "ModelA" instance.
>>> 
>>> model_b_6 = ModelB.objects.create(field_b="Value 6", child_field=model_a_2)
Traceback (most recent call last):
    raise ValueError(
ValueError: Cannot assign "<ModelA: ModelA object (2)>": "ModelB.child_field" must be a "ModelB" instance.

Upvotes: 1

Related Questions