Specifying model relationship as string vs concrete model class

47 views
Skip to first unread message

Mohit Solanki

unread,
Apr 6, 2019, 11:53:45 PM4/6/19
to django-d...@googlegroups.com
Since Django allows specifying relationship between models by both as a string or by a model class
"models.Foreignkey('User') vs "models.Foreignkey(User)". Which one is preferred and recommend and what are the downsides of choosing one over the other? In documentation all the examples are of the second form but i have seen ppl specifying relationships in string. Can someone please elaborate more on this?

Regards,
Mohit Solanki

Mohit Solanki

unread,
Apr 7, 2019, 8:38:41 AM4/7/19
to Django developers (Contributions to Django itself)
I know this group is for django development, posting it here because I want to here from core django devs.

Collin Anderson

unread,
Apr 7, 2019, 1:39:17 PM4/7/19
to django-d...@googlegroups.com
models.Foreignkey(User) is a more pythonic and allows more better analysis by tools like flake8, but in some cases you need to create the ForeignKey before User is defined, so you _have_ to use a string. Example:


--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To post to this group, send email to django-d...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/CAKB6Ln-4rU2c%3DZL%3DTCbYfFZWG8fSDq4KP9DYhUc4TDFLNFdQtw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages