Anoop
Anoop

Reputation: 543

How to get the content type model name using the slug field

I would like to get the model name from the content type.

I have tried this ....

a=Module.objects.filter(slug="sales")

So it return SoftDeletionQueryset

So after that I just done the following

for x in a: print(x.content_type)

So it return "sales analytics". That is the content_type value in the Module.content_type field

I have the content_type values now ..... The content type model having the 3 fields right ? app_label,model,name So I want to get the model name according to the content_type values –

Here is my code

class Module(BaseModel, SoftDeletionModel):
    id = models.AutoField(primary_key=True)
    name = models.CharField(
        _("Module Name"), max_length=50, default=False, unique=True)
    slug = models.SlugField(unique=True)
    display_name = models.CharField(
        _("Display Name"), max_length=50, default=False)
    content_type = models.ForeignKey(ContentType,
                                     blank=True, null=True, on_delete=models.CASCADE)
    parent_module_id = models.ForeignKey("Module",
                                         blank=True, null=True, on_delete=models.CASCADE)
    order = models.IntegerField(_("Order"), default=0, blank=True, null=True)

    class Meta:
        db_table = 'modules'

    def __str__(self):
        return "{0}".format(self.display_name)

Upvotes: 2

Views: 471

Answers (1)

Nikita Davydov
Nikita Davydov

Reputation: 957

I don't really understand the question, but I will try to answer

You use print() and it returns __str__ func result.

If you want to get the model name you have to use this code or content_type

modules = Module.objects.filter(slug="sales")
for m in modules:
   print(m.name)
   print(m.content_type)

If you mean exactly classname
For that use .__class__.__name__ or Module.__name__

Upvotes: 1

Related Questions