How to write a Pandas Dataframe to Django model

后端 未结 3 1666
借酒劲吻你
借酒劲吻你 2020-12-13 00:52

I have been using pandas in python and I usually write a dataframe to my db table as below. I am now now migrating to Django, how can I write the same dataframe to a table t

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 01:43

    My solution using pickle and optionally zlib for compression

    import pickle
    #optional
    #import zlib
    
    class SuperModel(models.Model):
        DFToStore = models.BinaryField(default=None, null=True, blank=True)
    
        def save(self, *args, **kwargs):
            if not isinstance(self.DFToStore, (bytes)):
                self.DFToStore = pickle.dumps(self.DFToStore)
                #optional with compression
                #self.DFToStore = zlib.compress(pickle.dumps(self.DFToStore))
            super(SuperModel, self).save(*args, **kwargs)
    
        def get_DFToStore(self):
            if isinstance(self.DFToStore, (bytes)):
                return pickle.loads(self.DFToStore)
                #optional with compression
                #return pickle.loads(zlib.decompress(self.DFToStore))
            if not isinstance(self.DFToStore, (bytes)):
                return self.DFToStore
    
    
     
    

提交回复
热议问题