Reputation: 2589
I have a app called C3po. I'm working on the model "Article". In this model I want to create a ForeignKey field with a custom related_name to a model in another app called Lea. To make sure the related_name is unique, I want to name it "c3po_articles". But I don't want to hard code the app name c3po. How can I get the folder / app name in a dynamic way ? Do I use __file__ and split it or is there a more elegant method ?
Thank you for your help :)
Upvotes: 1
Views: 1129
Reputation: 239290
The related_name
attribute supports automatic string interpolation with two variables: app_label
and class
. For example:
models.ForeignKey(FooModel, related_name='%(app_label)s_%(class)s_foo')
Now, I'm honestly not sure if Django will let you just include one or the other, i.e. just '%(app_label)s_foo'
, but you can try. (After a closer look at the docs, I highly doubt it. It seems like it's both or neither, but still, test it yourself and see.)
See: https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
EDIT
Actually, after thinking about it more, for your case, you could just use '%(app_label)s_%(class)ss'
, which should net you c3po_articles
as the related_name
.
Upvotes: 1