Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting in python

I looked at similar question on SO but none of them answer my problem. For Ex. How do you cast an instance to a derived class? . But the answer doesn't seem to be what I want.

Here is my situation. I have a class structure like in Django

class Base:
     ...some stuff...

class Derived(Base):
     ...some more stuff...

Now when I make some queries in Django, I always get objects of Base class.

 baseobj = get_object_or_404(Base, id = sid)

At runtime I can also encounter "Derived" objects which have some extra properties. I'm able to figure out if an object is Base or derived(there is sufficient info in Base class object). But how should I access those extra fields which are present only in Derived class. I'm not able to downcast "Base" -> "Derived". How should I handle it?

EDIT:

I figured out the problem. Django stores "additional properties" of Derived class in a separate table. Hence problem arose due to this line of code.

baseobj = get_object_or_404(Base, id = sid)

baseobj will always be of Base class and will not have any properties of Derived class. I have to make an additional query to get the Derived class object.

baseobj = get_object_or_404(Base, id = sid)
if baseobj.isDerivedType:
      derivedobj = get_object_or_404(Derived, id = sid)
like image 810
Neo Avatar asked Dec 19 '25 17:12

Neo


1 Answers

This sort of inheritance in Django-land smells like multi-table inheritance to me. According to the doc, assuming everything is wired properly, you should be able to do:

baseobj.derived    # note: small 'd'
like image 63
Santa Avatar answered Dec 21 '25 07:12

Santa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!