A OneToOneField is essentially the same as a ForeignKey, with the exception that it always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list.
| 1341 | |
| 1342 | |
| 1343 | class OneToOneField(ForeignKey): |
| 1344 | """ |
| 1345 | A OneToOneField is essentially the same as a ForeignKey, with the exception |
| 1346 | that it always carries a "unique" constraint with it and the reverse |
| 1347 | relation always returns the object pointed to (since there will only ever |
| 1348 | be one), rather than returning a list. |
| 1349 | """ |
| 1350 | |
| 1351 | # Field flags |
| 1352 | many_to_many = False |
| 1353 | many_to_one = False |
| 1354 | one_to_many = False |
| 1355 | one_to_one = True |
| 1356 | |
| 1357 | related_accessor_class = ReverseOneToOneDescriptor |
| 1358 | forward_related_accessor_class = ForwardOneToOneDescriptor |
| 1359 | rel_class = OneToOneRel |
| 1360 | |
| 1361 | description = _("One-to-one relationship") |
| 1362 | |
| 1363 | def __init__(self, to, on_delete, to_field=None, **kwargs): |
| 1364 | kwargs["unique"] = True |
| 1365 | super().__init__(to, on_delete, to_field=to_field, **kwargs) |
| 1366 | |
| 1367 | def deconstruct(self): |
| 1368 | name, path, args, kwargs = super().deconstruct() |
| 1369 | if "unique" in kwargs: |
| 1370 | del kwargs["unique"] |
| 1371 | return name, path, args, kwargs |
| 1372 | |
| 1373 | def formfield(self, **kwargs): |
| 1374 | if self.remote_field.parent_link: |
| 1375 | return None |
| 1376 | return super().formfield(**kwargs) |
| 1377 | |
| 1378 | def save_form_data(self, instance, data): |
| 1379 | if isinstance(data, self.remote_field.model): |
| 1380 | setattr(instance, self.name, data) |
| 1381 | else: |
| 1382 | setattr(instance, self.attname, data) |
| 1383 | # Remote field object must be cleared otherwise Model.save() |
| 1384 | # will reassign attname using the related object pk. |
| 1385 | if data is None: |
| 1386 | setattr(instance, self.name, data) |
| 1387 | |
| 1388 | def _check_unique(self, **kwargs): |
| 1389 | # Override ForeignKey since check isn't applicable here. |
| 1390 | return [] |
| 1391 | |
| 1392 | |
| 1393 | def create_many_to_many_intermediary_model(field, klass): |
no outgoing calls