【问题标题】:How to get the content type model name using the slug field如何使用 slug 字段获取内容类型模型名称
【发布时间】:2019-11-07 08:38:03
【问题描述】:

我想从内容类型中获取模型名称。

这个我试过了....

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

所以它返回 SoftDeletionQueryset

所以在那之后我只是做了以下

for x in a: print(x.content_type)

所以它返回“销售分析”。即 Module.content_type 字段中的 content_type 值

我现在有 content_type 值.....内容类型模型有 3 个字段对吗? app_label,model,name 所以我想根据 content_type 的值来获取模型名——

这是我的代码

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)

【问题讨论】:

    标签: django django-models django-contenttypes


    【解决方案1】:

    我不是很明白这个问题,但我会尽力回答

    您使用 print() 并返回 __str__ func 结果。

    如果你想获得模型名称,你必须使用这个代码或 content_type

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

    如果你的意思是类名
    为此使用.__class__.__name__Module.__name__

    【讨论】:

    • 您好,我会解释一下......我现在有 content_type 值......内容类型模型有 3 个字段对吗? app_label,model,name 所以我想根据 content_type 值获取模型名称
    • 我还是不清楚,抱歉您想使用 content_type 作为过滤器来查询 Module 表吗? Module.objects.filter(content_type__name="some_name") ?
    猜你喜欢
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多