Opened 14 years ago
Closed 14 years ago
#13527 closed (wontfix)
Allow column on ForeignKey
Reported by: | malthe | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.1 |
Severity: | 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
Currently, on the many-side of a ManyToOne
relation, the underlying value of the relation is always stored in fieldname_id
(both on the database side and in the ORM). However, this value will often be meaningful on its own and it should be possible to explicitly provide a name, e.g. from_field
(the database column name would be "%(from_field)s_id".)
The following implements this:
class CustomForeignKey(models.ForeignKey): def __init__(self, *args, **kwargs): self.from_field = kwargs.pop('from_field') if self.from_field: kwargs.setdefault('db_column', "%s_id" % self.from_field) return super(CustomForeignKey, self).__init__(*args, **kwargs) def get_attname(self): return self.from_field or "%s_id" % self.name
Note:
See TracTickets
for help on using tickets.
I'm afraid I don't see the value here. You can name the attribute anything you want (using the model definition), and you can specify whatever database column name you want (using db_column); the "append _id to the field name" is a helpful convention so you always know how you can retrieve the underlying key value.
Ultimately, this is cosmetic change that allows the user to define potentially confusing models (why doesn't object_id retrieve the key for the related object?), and introduces extra complexity to validation (since from_field can't clash with the attribute or field name of any other field on the model).