Opened 3 months ago
Last modified 7 weeks ago
#35956 new New feature
Add composite foreign keys
Description ¶
This is a follow up to #373 (CompositePrimaryKey).
Now that composite primary keys are merged, it would be great to be able to create foreign keys referencing them through the Django ORM.
My proposal is to add 2 parameters to ForeignKey
: from_fields
and to_fields
.
They would map to the underlying ForeignObject
's from_fields
, to_fields
parameters.
If a ForeignKey
has multiple fields, it acts as a virtual field, meaning it doesn't create a database column automatically.
According to the ticket's flags, the next step(s) to move this issue forward are:
- To provide a patch by sending a pull request. Claim the ticket when you start working so that someone else doesn't duplicate effort. Before sending a pull request, review your work against the patch review checklist. Check the "Has patch" flag on the ticket after sending a pull request and include a link to the pull request in the ticket comment when making that update. The usual format is:
[https://github.com/django/django/pull/#### PR]
.
Change History (4)
comment:1 by , 2 months ago
Triage Stage: | Unreviewed → Accepted |
---|
follow-up: 4 comment:2 by , 8 weeks ago
comment:3 by , 8 weeks ago
Cc: | added |
---|
comment:4 by , 7 weeks ago
Replying to Mariusz Felisiak:
Do we need these parameters?
CompositePrimaryKey
is always a primary key so its fields should be detected automatically, IMO, the following example should work:
class Release(models.Model): pk = models.CompositePrimaryKey("version", "name") version = models.IntegerField() name = models.CharField(max_length=20) class RefRelease(models.Model): release = models.ForeignKey("Release", models.CASCADE)
The issue with this example is RefRelease
must have 2 fields matching the CompositePrimaryKey
(an IntegerField()
and a CharField(max_length=20)
).
So release
would need to create 2 fields implicitly and I think that's too restrictive.
We should allow sharing fields between composite foreign keys.
For example, in a multi-tenant app where each model has a CompositePrimaryKey("tenant_id", "id")
, the tenant_id
field should be shared between composite foreign keys.
Let me know what you think about this, I'm happy to consider alternatives.
Replying to Csirmaz Bendegúz:
Do we need these parameters?
CompositePrimaryKey
is always a primary key so its fields should be detected automatically, IMO, the following example should work: