Web2py insertion methods

Web2py documents have two methods for inserting into a database

db.tbl[0] = newRow 

and

 db.tbl.insert(newRowAsDict) 

The documentation implies that they are synonyms, but they seem different. First, the insert method throws an exception if newRow contains fields that are not in the table. The .insert method also returns the id of the added row, where there is no assignment.

  • This is the intended behavior.
  • How can I get the identifier if I use the assignment method?
  • Is the assignment method devoid of?
+6
source share
3 answers

A little run shows the difference between the two:

For: db.tbl[0] = dict(name='something')

 File "/var/web2py/gluon/globals.py", line 172, in <lambda> self._caller = lambda f: f() File "/var/web2py/applications/myapp/controllers/default.py", line 114, in test db.tbl[0] = dict(name='something') File "/var/web2py/gluon/dal.py", line 5531, in __setitem__ self.insert(**self._filter_fields(value)) File "/var/web2py/gluon/dal.py", line 5605, in insert return self._db._adapter.insert(self,self._listify(fields)) 

For: db.tbl.insert(name='something')

 File "/var/web2py/gluon/globals.py", line 172, in <lambda> self._caller = lambda f: f() File "/var/web2py/applications/myapp/controllers/default.py", line 115, in test db.tbl.insert(name='something') File "/var/web2py/gluon/dal.py", line 5605, in insert return self._db._adapter.insert(self,self._listify(fields)) 

Both of them end up calling the same code to insert, so you will see that they run the same request:

 INSERT INTO tbl(name) VALUES ('something'); 

Since the first one has _filter_fields , as can be seen from the trace, it does not throw exceptions when there are fields that are not present in the table, and the other does.

Obviously, db.tbl[0] = newRow cannot return a value. You should just consider its shortcut for insertion, and its cousin db.tbl[x>0] extremely useful for updates and has the same notation, and this helps simplify the code.

+1
source

There is also

 db.tbl.insert(**db.tbl._filter_fields(newRowAsDict)) 

which will filter keys in newRowAsDict, ignoring unknown fields.

+4
source
  • This is the intended behavior.

Based on the code, this is similar. Using the assignment method, the fields are filtered, so they only try to insert the fields that belong to the table. This does not happen with the standard insert() method.

  • How can I get the identifier if I use the assignment method?

If you need an identifier, you are probably better off using the insert() method.

  • Is the assignment method devoid of?

I do not think so.

+2
source

Source: https://habr.com/ru/post/907430/


All Articles