How to get the current App name in models.py in Django?

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

Answers


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.


Need Your Help

Adding more than one JPanel in a single JFrame

java swing user-interface netbeans layout-manager

I have created a JFrame - now I want to add the 4 JPanel in that frame at a particular location. How can set the location of panels in the frame?

how to using javascript to get data from couchdb

javascript html couchdb heatmap

I have store some document in couchdb, and generate a view using map reduce. Every document in the view is in following structure :