| 175 | raise NotImplementedError('`create()` must be implemented.') |
| 176 | |
| 177 | def save(self, **kwargs): |
| 178 | assert hasattr(self, '_errors'), ( |
| 179 | 'You must call `.is_valid()` before calling `.save()`.' |
| 180 | ) |
| 181 | |
| 182 | assert not self.errors, ( |
| 183 | 'You cannot call `.save()` on a serializer with invalid data.' |
| 184 | ) |
| 185 | |
| 186 | # Guard against incorrect use of `serializer.save(commit=False)` |
| 187 | assert 'commit' not in kwargs, ( |
| 188 | "'commit' is not a valid keyword argument to the 'save()' method. " |
| 189 | "If you need to access data before committing to the database then " |
| 190 | "inspect 'serializer.validated_data' instead. " |
| 191 | "You can also pass additional keyword arguments to 'save()' if you " |
| 192 | "need to set extra attributes on the saved model instance. " |
| 193 | "For example: 'serializer.save(owner=request.user)'.'" |
| 194 | ) |
| 195 | |
| 196 | assert not hasattr(self, '_data'), ( |
| 197 | "You cannot call `.save()` after accessing `serializer.data`." |
| 198 | "If you need to access data before committing to the database then " |
| 199 | "inspect 'serializer.validated_data' instead. " |
| 200 | ) |
| 201 | |
| 202 | validated_data = {**self.validated_data, **kwargs} |
| 203 | |
| 204 | if self.instance is not None: |
| 205 | self.instance = self.update(self.instance, validated_data) |
| 206 | assert self.instance is not None, ( |
| 207 | '`update()` did not return an object instance.' |
| 208 | ) |
| 209 | else: |
| 210 | self.instance = self.create(validated_data) |
| 211 | assert self.instance is not None, ( |
| 212 | '`create()` did not return an object instance.' |
| 213 | ) |
| 214 | |
| 215 | return self.instance |
| 216 | |
| 217 | def is_valid(self, *, raise_exception=False): |
| 218 | assert hasattr(self, 'initial_data'), ( |