hey there -

what you're doing is suited by an included feature of SQLAlchemy called "single 
table inheritance", which will return to you instances of "Mammal" or 
AnimalModel object based on the value of "type".

see: 
https://docs.sqlalchemy.org/en/13/orm/inheritance.html#single-table-inheritance



On Thu, Jul 9, 2020, at 6:53 PM, Raghav wrote:
> Hello everyone, hope you're all doing well.
> 
> I have a table which has a type column. Based on that value I need to 
> instantiate a new class. I'm looking for a way to operate my SQLAlchemy 
> object through this new class.
> 
> Here's my model class: 
> ```
> class AnimalModel(Base):
>  __tablename__ = "animal"
>  id = Column(Integer, primary_key=True)
>  type = Column(String)
>  name = Column(String)
>  ...
> ```
> 
> Here is my python class.
> ```
> class Mammal(BaseAnimal):
>  def __init__(self, animal_model):
>  self.__dict__.update(animal_model.__dict__)
> 
>  def has_fur(self):
>  return True
> ```
> 
> Once I query the animal table and receive the `AnimalModel` object. I create 
> a new `BaseAnimal` class based on the type.
> 
> I need a way to merge or remap the `AnimalModel` object to the new 
> `BaseAnimal` object so that I can get my methods from `BaseAnimal` and I also 
> get to do table updates.
> 
> ```
> mammal = new Mammal(animal_model)
> mammal.has_fur()
> mammal.name = 'Whale' # SQL row update
> ```
> 
> What are some ways in which this can be achieved?
> 

> --
>  SQLAlchemy - 
>  The Python SQL Toolkit and Object Relational Mapper
> 
> http://www.sqlalchemy.org/
> 
>  To post example code, please provide an MCVE: Minimal, Complete, and 
> Verifiable Example. See http://stackoverflow.com/help/mcve for a full 
> description.
>  --- 
>  You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
>  To unsubscribe from this group and stop receiving emails from it, send an 
> email to sqlalchemy+unsubscr...@googlegroups.com.
>  To view this discussion on the web visit 
> https://groups.google.com/d/msgid/sqlalchemy/d429d258-27c2-4ebc-b469-681fedb2ce17n%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/sqlalchemy/d429d258-27c2-4ebc-b469-681fedb2ce17n%40googlegroups.com?utm_medium=email&utm_source=footer>.

-- 
SQLAlchemy - 
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sqlalchemy/2b829383-9330-4b41-a6c5-761d71117dbe%40www.fastmail.com.

Reply via email to