hi ![]()
i was wondering if there is a reason when we use a to_field in a ForeignKey, the target field is not enforeced to be NOT NULL
we ran some tests, like: Dry ORM and having null as target will silently save null in the fk column, so no relationship will form
so in the example you can see:
class Target(models.Model):
fk_target = models.IntegerField(null=True, unique=True)
class Child(models.Model):
target = models.ForeignKey(Target, on_delete=models.CASCADE, to_field="fk_target", null=True)
so Child has an fk to Target, but instead of pointing to the id field, it points to fk_target
but since fk_target is null=True, you can do this:
target_null = Target.objects.create(fk_target=None)
child_null = Child.objects.create(target=target_null)
which seems like a normal django code, but then you query child_null
child_null_refresh = Child.objects.get(pk=child_null.pk)
print(child_null_refresh.target)
# None
and there is no relationship
i think null=false should be enforced, or if there is a reason for it to not be, maybe a warning should be logged when creating a relationship to a null column
or at least document it
should mention that unique=True is already enforced here as you can see here: