【问题标题】:get class name for empty queryset in django在 django 中获取空查询集的类名
【发布时间】:2013-01-07 09:40:27
【问题描述】:

我有模型的空查询集学生

students = Students.objects.all()

如果上面的查询集是空的,那我怎样才能得到模型(类名)?

如何获取空查询集的模型名称?

编辑:

如何从查询集中获取应用名称?

【问题讨论】:

  • “我有模型 Student 的空查询集” - 不一定是空的,但 Students.objects.none() 始终是一个空查询集。

标签: python django django-models django-views


【解决方案1】:
>>> students = Students.objects.all()

# The queryset's model class:
>>> students.model
project.app.models.Student

# Name of the model class:
>>> students.model.__name__
'Student'

# Import path of the models module:
>>> students.model.__module__
'project.app.models'

# Django app name:
>>> students.model._meta.app_label
'app'

【讨论】:

  • 谢谢 jkbr。如何从查询集中获取应用名称?
  • 我希望这被记录在案...:/
  • 我在文档中的任何地方都没有找到这个,是否有显示 QuerySet 属性的页面?
  • @jakub-roztocil 我如何获得所有学生的姓名?如果模型有一个名为 name 的字段。
  • @Mojimi print(myqueryset.__dict__) 会有所帮助
【解决方案2】:
students.model

查询集有一个model 属性,可用于检索与其关联的模型。

【讨论】:

  • 如何在模板中做到这一点?
【解决方案3】:

你可以这样做:

students.model.__name__
>>> `Students`

【讨论】:

    【解决方案4】:

    从查询集中获取模型名称

    queryset.__dict__['model'].__name__
    

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 2021-12-10
      • 2020-08-06
      • 2013-04-22
      • 2014-01-25
      • 2010-11-26
      • 1970-01-01
      • 2021-06-06
      • 2012-04-14
      相关资源
      最近更新 更多