如何在python中获取类属性(Django Model)的类型

时间:2017-12-21 13:48:20

标签: python django

我有一个具有不同属性的Python类,但我似乎没有找到如何获取每个属性的类型。我想检查给定属性是否具有特定类型。

请注意我说的是课而不是实例。

让我们说我有这个课程:

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.'},
    )

如何检查短名称是否为model.CharField或model.Whatever?

2 个答案:

答案 0 :(得分:3)

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**

对于 django 相关项目,它就像

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

答案 1 :(得分:1)

请参阅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>