Code

Opened 4 years ago

Closed 4 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: UI/UX:

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

Attachments (0)

Change History (1)

comment:1 Changed 4 years ago by russellm

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to wontfix
  • Status changed from new to closed

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).

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.