简体   繁体   中英

How to get the type of a class property (Django Model) in python

I have a Python class with different attributes but I do not seem to find how to get the type of each of them. I want to check whether if a given attribute has an specific type.

Be aware that I am talking about the class and not an instance.

Let's say that I have this class:

class SvnProject(models.Model):
    '''
        SVN Projects model
    '''
    shortname = models.CharField(
        verbose_name='Repository name',
        help_text='An unique ID for the SVN repository.',
        max_length=256,
        primary_key=True,
        error_messages={'unique':'Repository with this name already exists.'},
    )

How can I check whether shortname is a model.CharField or a model.Whatever?

class Book:
    i = 0 # test class variable
    def __init__(self, title, price):
        self.title = title
        self.price = price
    ...

# let's check class variable type
# we can directly access Class variable by
# ClassName.class_variable with or without creating an object
print(isinstance(Book.i, int))
# it will print True as class variable **i** is an **integer**

book = Book('a', 1)

# class variable on an instance
print(isinstance(book.i, int))
# it will print True as class variable **i** is an **integer**

print(isinstance(book.price, float))
# it print False because price is integer

print(type(book.price))
# <type 'int'>

print(isinstance(book, Book))
# it will print True as book is an instance of class **Book**

For django related projects it would be like

from django.contrib.auth.models import User
from django.db.models.fields import AutoField

print(isinstance(User._meta.get_field('id'), AutoField))
# it will print True

See https://docs.djangoproject.com/en/2.0/ref/models/meta/#django.db.models.options.Options.get_field

>>> SvnProject._meta.get_field('shortname')
<django.db.models.fields.CharField: shortname>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM