#31207: Broken foreing key reference with multi-table inheritance (PostgreSQL,
Django 3.0)
-------------------------------------+-------------------------------------
Reporter: un.def | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: 3.0
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Simon Charette):
Something seems off with your models setup, unless `BaseModel` is abstract
then the `key` column will be defined on its table so it's simply not
possible to have a foreign key from `OtherModel` to `ChildModel` with a
`to_field='key'`.
It looks like something that happened to work by chance previously as the
foreign key could be pointing at an instance of `BaseModel` that isn't a
`ChildModel` so this breaks referential integrity; `to_field` should only
be allowed to point a local fields.
e.g.
{{{#!python
class BaseModel(models.Model):
key = models.IntegerField(unique=True)
class ChildModel(BaseModel):
pass
class OtherChildModel(BaseModel):
pass
class OtherModel(models.Model):
ref = models.ForeignKey(ChildModel, to_field='key')
>>> child = OtherChildModel.objects.create(key='foo')
>>> other = OtherModel.objects.create(ref=child.key)
>>> other.refresh_from_db()
>>> other.ref # raises ChildModel.DoesNotExist
}}}
Looks like what you are looking for is
{{{#!python
class BaseModel(models.Model):
key = models.IntegerField(unique=True)
class ChildModel(BaseModel):
pass
class OtherModel(models.Model):
ref = models.ForeignKey(BaseModel, to_field='key')
child_ref = ForeignObject(ChildModel, from_fields=('ref_id',),
to_fields=('basemodel_ptr_id',))
}}}
And that `ForeignKey` should be adjusted to prevent usage of `to_field`
pointing to non-local fields.
--
Ticket URL: <https://code.djangoproject.com/ticket/31207#comment:1>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/064.655cfea904a40733255952f9c7058663%40djangoproject.com.