How do I select the base class from the child object in Django (using model inheritance)
-
12-06-2021 - |
Question
I have a base model and one that inherits from it, similar in setup to this:
class Archive(models.Model):
pub_date = models.DateField()
class ArchiveB(Archive):
another_date = models.DateField()
How do I access the base class from the child class? For example:
archiveb_instance = ArchiveB.objects.get(pk=5)
base_instance = archiveb_instance.archive #This doesn't work.
According to the documentation its just a one-to-one relationship automatically created in the child so I figured it would let me go backwards. The reason I want this is because I have a third non-Archive model that has a foreignkey to Archive. I want the foreignkey to Archive because this way the third model can relate to any Archive, not just a specific Archive type.
Solution
i think you might be looking for archiveb_instance.archive_ptr
OTHER TIPS
They share the same PK, so just assign that to the field with _id
appended.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow