Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if values are valid before create()

Hi I'm trying to import lines from a CSV, but I can't handle type errors. For example, if you insert a string in a datetime field, I get this error in the create:

psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block

Despite handling errors with

try:
  my_module.create()
exception Except:
  #stuff
  pass

How can I check the values before I get to create or at least handle the error and take other actions. For the moment if I insert a field that is not present on a selection, I manage with try catch but I can't for data types

like image 970
Plaoo Avatar asked Dec 10 '25 11:12

Plaoo


1 Answers

There is a method load(fields, data) on BaseModel which you could extend.

class MyModel(models.Model):
    # if a new model
    _name = 'my.model'
    # if an extended model
    #  _inherit = 'my.model'

    def load(self, fields, data):
    """ Extended to do stuff to the data before importing it to database"""
        # do stuff like converting weird data input
        clean_data = self.clean_data(data)
        # call super with cleaned data afterwards
        return super(MyClass, self).load(fields, clean_data)
like image 64
CZoellner Avatar answered Dec 12 '25 02:12

CZoellner



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!