How to introspect django model fields?

后端 未结 4 1580
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 17:01

I am trying to obtain class information on a field inside a model, when I only know name of the field and name of the model (both plain strings). How is it possible?

4条回答
  •  忘掉有多难
    2020-12-07 17:24

    django.db.models.loading.get_model() has been removed in django 1.9. You are supposed to use django.apps instead.

    'get_field_by_name is an unofficial API that has been deprecated in Django 1.10. You may be able to replace it with '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()
    (, , , ) 
    

    link to issue

提交回复
热议问题