0

I'm trying to create a mechanism of duplicating sqlalchemy models in flask. To do so, I'm running the following logic:

class Model:
      primitive_type = (int, bool, float, str)
      def copy(self):
          copy = type(self)()
          for key, val in self.__dict__.items():
              if not key.startswith('_') and isinstance(val, Model.primitive_type):
                 copy.__setattr__(key, val)
          return copy

Then I've a model named sensor which is an abstract model:

class Sensor(db.Model):
     __tablename__ = 'sensor'

     id = db.Column(db.Integer, primary_key=True)
     device_id = db.Column(db.Integer, db.ForeignKey('device.id'))
     type = db.Column(db.String(128), nullable=False)

     __mapper_args__ = {
         'polymorphic_identity': 'sensor',
         'polymorphic_on': type
     }

And finally I've the sensor itself which ineriths both from Model and Sensor:

class Pnt(Model, Sensor):
     __tablename__ = 'pnt'

     id = db.Column(db.Integer, db.ForeignKey('sensor.id'), primary_key=True)
     host_ip = db.Column(db.String(100), nullable=False, info={'label': "Ip"})
     ...
     def copy(self):
         copy = super().copy()
         return copy

The problem is that super().copy() returns the values from Sensor and not from Pnt. This method isn't working only in this case. Any help would be appreciated.

Miguel Andrade
  • 346
  • 3
  • 13
  • Tried to reproduce it and come to a different result. What is missing? Is the host_ip attribute missing? What do you intend to do with the copy? Do you just want to save a copy in the database? – Detlef Feb 01 '21 at 23:05
  • Thank you @Detlef. Yes the host_ip is missing. I have not any attribute of Pnt. Yes I want to duplicate Pnt and insert it in database with a new id. – Miguel Andrade Feb 02 '21 at 10:45
  • As I said, I have the Pnt attributes with your code. Please take a look at [this](https://stackoverflow.com/questions/28871406/how-to-clone-a-sqlalchemy-db-object-with-new-primary-key) example especially the top answer. I think it's an excellent solution. – Detlef Feb 02 '21 at 10:53

0 Answers0