Opened 2 years ago
Closed 2 years ago
#34614 closed Bug (worksforme)
Natural keys for nullable foreign keys
| Reported by: | Martin Beroiz | Owned by: | nobody |
|---|---|---|---|
| Component: | Core (Serialization) | Version: | 4.2 |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
I found that if a fixture has a model with a nullable foreign key (FK) to a model with natural keys, loaddata fails to load the first object.
For example, slightly modifying the docs example:
class PersonManager(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
class Person(models.Model):
name = models.CharField(max_length=100, unique=True)
objects = PersonManager()
def natural_key(self):
return (self.name,)
class Book(models.Model):
name = models.CharField(max_length=100)
author = models.ForeignKey(Person, on_delete=models.CASCADE, null=True)
(notice the null=True addition to Book)
Then this fixture will fail when attempting to load with loaddata
[
{
"model": "myapp.book",
"fields": {
"name": "I Ching",
"author": null,
}
},
]
Notice that "author": [null] in the fixture does not fix it either, since it will pass None to the manager's get_by_natural_key. Returning None from get_by_natural_key doesn't help either.
If this is a feature, and models with natural keys can't ever be referenced by other models with a _nullable_ FK to them, I think it should probably be explicit in the documentation.
Change History (1)
comment:1 by , 2 years ago
| Component: | Uncategorized → Core (Serialization) |
|---|---|
| Resolution: | → worksforme |
| Status: | new → closed |
Thanks for the ticket, however
"author": nullworks for me (checked on Django 4.2.2). You can try to use one of support channels when folks should help you debug.