Specifying model relationship as string vs concrete model?

18 views
Skip to first unread message

Mohit Solanki

unread,
Apr 6, 2019, 11:43:32 PM4/6/19
to Django users
Since Django provides two ways of specifying model relationship, 

models.ForeignKey('User') vs models.ForeignKey(User)

Which one is more preferred and recommended? Is there any upside or downside of choosing one over the other?  In Django documentation, all the example are of the second form but I have seen many people specifying the relationship as a string. Can Someone please elaborate more on this?

Regards,

Mohit

Mike Dewhirst

unread,
Apr 7, 2019, 12:38:00 AM4/7/19
to django...@googlegroups.com
Using the class means you have to import it first. I have stuck to the string version since encountering circular import errors some time ago. Django is smart enough to get it right so I don't even think about it.

YMMV

Mike

Connected by Motorola
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/06988f5c-9ad0-47b1-9216-5f689abb1720%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

PASCUAL Eric

unread,
Apr 7, 2019, 4:49:43 AM4/7/19
to django...@googlegroups.com
Hi Mohit,

The only situations where I have used strings are forward declarations or potential reference loops.

Intuitively I'd say that referencing models by their name adds a slight overhead for class lookup. But since this is supposed to happen only when the model definition is loaded (fields are class level attributes), there are chances that there is no impact on performances during the application normal operation. The impact should be on the application start phase, but it's probably neglectable compared to the overall start time. 

Since I've never done any real timing about this point, nor studied Django source code to identify the real mechanism, I'm strongly interested in other opinions... especially if my analysis is wrong 😉

Best

Eric


From: django...@googlegroups.com <django...@googlegroups.com> on behalf of Mohit Solanki <mohitso...@gmail.com>
Sent: Sunday, April 7, 2019 05:43
To: Django users
Subject: Specifying model relationship as string vs concrete model?
 
--
Reply all
Reply to author
Forward
0 new messages