代码之家  ›  专栏  ›  技术社区  ›  Evgeny

如何反思django模型域?

  •  35
  • Evgeny  · 技术社区  · 16 年前

    当我只知道字段名和模型名(都是纯字符串)时,我正试图获取模型中字段的类信息。怎么可能?

    我可以动态加载模型:

    from django.db import models
    model = models.get_model('myapp','mymodel')
    

    现在我有了字段-“myfield”-我如何得到该字段的类?

    如果字段是关系字段-如何获取相关字段?

    谢谢大家!

    4 回复  |  直到 7 年前
        1
  •  71
  •   UvaCiclopica Anurag Uniyal    7 年前

    你可以用模特的 _meta 属性以获取字段对象,而从字段可以获取关系以及更多信息,例如,考虑一个employee表,该表具有department表的外键

    In [1]: from django.db import models
    
    In [2]: model = models.get_model('timeapp', 'Employee')
    
    In [3]: dep_field = model._meta.get_field_by_name('department')
    
    In [4]: dep_field[0].target_field
    Out[4]: 'id'
    
    In [5]: dep_field[0].related_model
    Out[5]: <class 'timesite.timeapp.models.Department'>
    

    来自django/db/models/options.py

    def get_field_by_name(self, name):
        """
        Returns the (field_object, model, direct, m2m), where field_object is
        the Field instance for the given name, model is the model containing
        this field (None for local fields), direct is True if the field exists
        on this model, and m2m is True for many-to-many relations. When
        'direct' is False, 'field_object' is the corresponding RelatedObject
        for this field (since the field doesn't have an instance associated
        with it).
    
        Uses a cache internally, so after the first access, this is very fast.
        """
    
        2
  •  6
  •   tobltobs    10 年前

    来自Anurag Uniyal的答案 get_field_by_name 现在(5年后)已经过时了 按名称获取字段 已弃用。 Django会给你以下提示:

    removedindjango110警告:“按名称获取字段”是一个非官方API 那已经被弃用了。你可以用 '获取字段()'

    API文档 get_field here .

        3
  •  2
  •   user1847    8 年前

    如果您想查看django模型对象上的所有字段,只需调用 ._meta.get_fields() 在类(或实例化的模型对象)上获取所有字段的列表。这个api是django的最新版本。

    例子:

    from django.contrib.auth.models import User
    User._meta.get_fields()
    

    这将返回所有模型字段的元组。可以找到文档 HERE .

        4
  •  1
  •   Gambitier    7 年前

    django 1.9中删除了django.db.models.loading.get_model()。 你应该改用django.apps。

    'get_field_by_name是一个在django 1.10中被弃用的非官方api。您可以将其替换为“get_field()”

    >>> from django.apps import apps
    >>> from polls.models import Question
    >>> QuestionModel = apps.get_model('polls','Question')
    >>> QuestionModel._meta.get_field('pub_date')
    >>> QuestionModel._meta.get_fields()
    (<ManyToOneRel: polls.choice>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.CharField: question_text>, <django.db.models.fields.DateTimeField: pub_date>) 
    

    link to issue

    推荐文章