How to get appname from model in django

Question:

I have this code

class Option(models.Model):
  option_text  = models.CharField(max_length=400)
  option_num   = models.IntegerField()
  # add field to hold image or a image url in future

  class Meta:
        app_label = 'myapp'

if i have Options model in my view i want to get the appname from it

Asked By: Karl

||

Answers:

from django.contrib.contenttypes.models import ContentType

ct = ContentType.objects.get_for_model(option_instance)
print(ct.app_label)

or

option_instance._meta.app_label
Answered By: Sergey Gornostaev

If you have an instance of your object, you can quite easily get the app_label from _meta

o = Option.objects.all()[0]
print o._meta.app_label

There is a host of other usefull information in there. In the shell type help(a._meta) to see them all

Answered By: e4c5

2022

app_label = self.__module__.split('.')[0]

Works in every view scenario.

Answered By: alias51
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.