Pradeeshnarayan
Pradeeshnarayan

Reputation: 1235

Duplicate a record and its references in web2py

In my web2py application I have a requirement to duplicate a record and all its references. For example one user has a product (sponserid is the user). and this product has so many features stored in other tables (reference to product id).

And my requirement is if an another user is copying this product, the a new record will generate in the product table with new productid and new sponserid. And all the reference table records will also duplicate with the new product id. Effectively a duplicate entry is creating in all the tables only change is product id and sponserid.

The product table fields will change. So I have to write a dynamic query.

If I can write a code like below

product = db(db.tbl_product.id==productid).select(db.tbl_product.ALL).first()
newproduct = db.tbl_product.insert(sponserid=newsponserid)
for field,value in product.iteritems():
    if field!='sponserid':
        db(db.tbl_product.id==newproduct).update(field=value)

But I cannot refer a field name like this in the update function.

Also I would like to know if there is any other better logic to achieve this requirement. I would greatly appreciate any suggestions.

Upvotes: 0

Views: 1491

Answers (1)

Anthony
Anthony

Reputation: 25536

For the specific problem of using the .update() method when the field name is stored in a variable, you can do:

db(db.tbl_product.id==newproduct).update(**{field: value})

But an easier approach altogether would be something like this:

product = db(db.tbl_product.id==productid).select(db.tbl_product.ALL).first()
product.update(sponserid=newsponserid)
db.tbl_product.insert(**db.tbl_product._filter_fields(product))

The .update() method applied to the Row object updates only the Row object, not the original record in the db. The ._filter_fields() method of the table takes a record (Row, Storage, or plain dict) and returns a dict including only the fields that belong to the table (it also filters out the id field, which the db will auto-generate).

Upvotes: 3

Related Questions