Updating existing rows¶
In DataJoint, the principal way of replacing data is by delete
and insert
. This approach observes referential integrity constraints.
In some cases, it becomes necessary to deliberately correct existing values. The update1
method accomplishes this. The method should only be used to fix problems, and not as part of a regular workflow. When updating an entry, make sure that any information stored in dependent tables that depends on the update values is properly updated as well.
Syntax:
table.update1(record)
Here record
is a dict
specifying the primary key values for identifying what record to update and the values that should be updated. The entry must already exist.
Example¶
Let’s create the Student
table and populate a few entries.
import datajoint as dj
schema = dj.schema('test_update')
@schema
class Student(dj.Manual):
definition = """
student_id : int
---
full_name : varchar(100) # last_name, first_name middle_name
phone="": varchar(20)
sex : enum('female', 'male')
"""
Student.insert1(dict(student_id=303, full_name="Rosen, Rose", sex="female"))
Student.insert1(dict(student_id=304, full_name="Rosen, Rose", sex="male", phone="(813)555-3744"))
Student()
We can now update some values. Note that you must specify the primary key and the entry must already exist.
Student.update1(dict(student_id=303, phone="(813)555-7133"))
Student.update1(dict(student_id=304, full_name="Ramesh, Henry"))
Student()
If the entry does not exist or if the primary key value is not specified, update1
raises errors:
Student.update1(dict(student_id=305, phone="(800)555-3377"))
---------------------------------------------------------------------------
DataJointError Traceback (most recent call last)
<ipython-input-6-c3ba2ed335d9> in <module>
----> 1 Student.update1(dict(student_id=305, phone="(800)555-3377"))
~/dev/datajoint-python/datajoint/table.py in update1(self, row)
237 key = {k: row[k] for k in self.primary_key}
238 if len(self & key) != 1:
--> 239 raise DataJointError('Update entry must exist.')
240 # UPDATE query
241 row = [self.__make_placeholder(k, v) for k, v in row.items() if k not in self.primary_key]
DataJointError: Update entry must exist.
Student.update1(dict(phone="(800)555-3377"))
---------------------------------------------------------------------------
DataJointError Traceback (most recent call last)
<ipython-input-7-780ca578d6bf> in <module>
----> 1 Student.update1(dict(phone="(800)555-3377"))
~/dev/datajoint-python/datajoint/table.py in update1(self, row)
228 raise DataJointError('The argument of update1 must be dict-like.')
229 if not set(row).issuperset(self.primary_key):
--> 230 raise DataJointError('The argument of update1 must supply all primary key values.')
231 try:
232 raise DataJointError('Attribute `%s` not found.' % next(k for k in row if k not in self.heading.names))
DataJointError: The argument of update1 must supply all primary key values.