0

I have two models(classes) that one inherits from another. GRESubjectCertificate as parent

class GRESubjectCertificate(LanguageCertificate):
    quantitative = models.PositiveSmallIntegerField()

    verbal = models.PositiveSmallIntegerField()

    analytical_writing = models.DecimalField(
        max_digits=2, decimal_places=1,
    )

    total = models.PositiveSmallIntegerField()

and GREBiologyCertitficate as child:

class GREBiologyCertificate(GRESubjectCertificate):
    cellular_and_molecular = models.PositiveSmallIntegerField()

    organismal = models.PositiveSmallIntegerField()

    ecology_and_evolution = models.PositiveSmallIntegerField()

I want to cast an object from GREBiologyCertificate to GRESubjectCertificate by parent class name in lower but it does not work. I have used before this solution to convert child object to parent object but now it fails.

instance1 = GREBiologyCertificate()

instance2 = instance1.gresubjectcertificate

'GREBiologyCertificate' object has no attribute 'gresubjectcertificate'

Edit1: Below example works without problem.

class A():
    number = models.PositiveSmallIntegerField()
class B(A):
    factor = models.PositiveSmallIntegerField()

instance1 = B()
instance2 = instance1.a

instance2 will be a instance of class A.

1 Answers1

0

The child object inherits from the parent class, but what do you mean by "convert child to parent object"? If you are simply trying to access properties of the parent class you can do it like normal, since GREBiologyCertificate inherits from GRESubjectCertificate. For example, if you wanted to access the "total" attribute from GRESubjectCertificate you could:

instance1.total

Does this help? If you only want to create an instance of the parent class, is there a reason you don't want to do:

instance2 = GRESubjectCertificate()
Rolv Apneseth
  • 2,078
  • 2
  • 7
  • 19
  • No.I want to cast child instance to parent instance. in python it is possible to get it as an attribute of child instance. May be i asked in bad way and by bad words. – Hossein Mohammadi Oct 11 '20 at 07:56
  • I'm sorry I don't understand. Why do you not want to just use `instance2 = GRESubjectCertificate()`? I don't believe it is possible to instantiate a parent class object from a child class object. – Rolv Apneseth Oct 11 '20 at 15:28