【问题标题】:Get all fields of a model in Django Shell在 Django Shell 中获取模型的所有字段
【发布时间】:2021-07-30 11:16:57
【问题描述】:

是否可以在 Django Shell 中输出特定模型的所有字段的名称? 比如如何从User模型中获取字段:

>>> from django.contrib.auth.models import User

我知道我可以通过访问相应应用的models.py 来获取它,但我可以更方便地在同一位置获取所有应用的型号信息。

【问题讨论】:

    标签: django django-models django-shell


    【解决方案1】:

    返回User 模型的字段对象列表。使用:

    field_names = User._meta.get_fields()
    

    要返回User 模型的字段名称列表,请使用:

    field_names = [f.name for f in User._meta.get_fields()]
    

    【讨论】:

    • 上面写着AttributeError: type object 'User' has no attribute '__meta'
    • @SayyorY 只使用一个下划线。 __ --> _
    • 不错的解决方案。对于您的模型,这也应该有效(但不在列表中):YourModel.__dict__['doc']
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2011-04-08
    • 2015-12-30
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多