Search code examples
djangodjango-models

How to get a list of the fields in a Django model?


I've defined a User class which (ultimately) inherits from models.Model. I want to get a list of all the fields defined for this model. For example, phone_number = CharField(max_length=20). Basically, I want to retrieve anything that inherits from the Field class.

I thought I'd be able to retrieve these by taking advantage of inspect.getmembers(model), but the list it returns doesn't contain any of these fields. It looks like Django has already gotten a hold of the class and added all its magic attributes and stripped out what's actually been defined. So... how can I get these fields? They probably have a function for retrieving them for their own internal purposes?


Solution

  • As most of answers are outdated I'll try to update you on Django 2.2 Here posts- your app (posts, blog, shop, etc.)

    1) From model link: https://docs.djangoproject.com/en/stable/ref/models/meta/

    from posts.model import BlogPost
    
    all_fields = BlogPost._meta.fields
    #or
    all_fields = BlogPost._meta.get_fields()
    

    Note that:

    all_fields=BlogPost._meta.get_fields()
    

    Will also get some relationships, which, for ex: you can not display in a view.
    As in my case:

    Organisation._meta.fields
    (<django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...
    

    and

    Organisation._meta.get_fields()
    (<ManyToOneRel: crm.activity>, <django.db.models.fields.AutoField: id>, <django.db.models.fields.DateField: created>...
    

    2) From instance

    from posts.model import BlogPost
    
    bp = BlogPost()
    all_fields = bp._meta.fields
    

    3) From parent model

    Let's suppose that we have Post as the parent model and you want to see all the fields in a list, and have the parent fields to be read-only in Edit mode.

    from django.contrib import admin
    from posts.model import BlogPost 
    
    @admin.register(BlogPost)
    class BlogPost(admin.ModelAdmin):
        all_fields = [f.name for f in Organisation._meta.fields]
        parent_fields = BlogPost.get_deferred_fields(BlogPost)
    
        list_display = all_fields
        read_only = parent_fields