Opened 11 years ago

Closed 11 years ago

Last modified 11 years ago

#3103 closed enhancement (wontfix)

[patch]: Remove restriction on string name for relationship fields.

Reported by: Eric Van Dewoestine <ervandew@…> Owned by: Adrian Holovaty
Component: Database layer (models, ORM) Version: master
Severity: normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


Patch based on development version 4051.

As described in the many-to-one relationships doc, django currently has the following restriction:

If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself:


Note, however, that you can only use strings to refer to models in the same file -- you cannot use a string to reference a model in a different
application, or to reference a model that has been imported from elsewhere.

The attached patch removes this restriction allowing one to do something like:

class Car(models.Model):
    manufacturer = models.ForeignKey('mysite.myotherapp.models.Manufacturer')

Attachments (1) (423 bytes) - added by Eric Van Dewoestine <ervandew@…> 11 years ago.

Download all attachments as: .zip

Change History (4)

Changed 11 years ago by Eric Van Dewoestine <ervandew@…>

Attachment: added

comment:1 Changed 11 years ago by Eric Van Dewoestine <ervandew@…>

note: patch is for file django/db/models/fields/

comment:2 Changed 11 years ago by Russell Keith-Magee

Resolution: wontfix
Status: newclosed

The restriction on forward declared models is by design.

Forward declarations of a model in the same applicaiton is required because there might be circular dependencies between models. However, applications themselves should be self contained. Any dependencies on other applications should be relatively simple 'prerequisites' - for example, assuming that contrib.auth is installed.

If you have two applications that are co-dependent, it's a pretty good indication that you actually have 1 application, not two, and the two applications should be merged.

comment:3 Changed 11 years ago by Eric Van Dewoestine <ervandew@…>

I am actually using this patch in relation to another patch I made (which I have not submitted).

The dependent patch adds an alternative to the contrib.auth.User.get_profile that instead conditionaly adds a direct relationship to a settings defined profile model. This allows for running database queries across the auth user table onto the now joined profile:

Poll.objects.filter(userprofilemyfield='my value')

If the rejection of this patch is based solely on assumed 'best practices', should the django code be dictating this? Or does the added flexibilty for users out weight that?

I understand if you still don't want to apply the patch, but I don't see any inherent downside.

Note: See TracTickets for help on using tickets.
Back to Top