简体   繁体   English

获取 Django 模型字段的 Python 类型?

[英]Get Python type of Django's model field?

How can I get corresponding Python type of a Django model's field class ?如何获取 Django 模型的字段类的相应 Python 类型?

from django.db import models

class MyModel(models.Model):
    value = models.DecimalField()

type(MyModel._meta.get_field('value'))  # <class 'django.db.models.fields.DecimalField'>

I'm looking how can I get corresponding python type for field's value - decimal.Decimal in this case.我正在寻找如何获得字段值的相应 python 类型 - 在这种情况下为decimal.Decimal

Any idea ?任何的想法 ?

ps I've attempted to work around this with field's default attribute, but it probably won't work in all cases where field has no default value defined. ps 我试图用字段的default属性解决这个问题,但它可能不适用于所有没有定义字段默认值的情况。

I don't think you can decide the actual python type programmatically there.我不认为你可以在那里以编程方式决定实际的 python 类型。 Part of this is due to python's dynamic type.部分原因是python的动态类型。 If you look at the doc for converting values to python objects , there is no hard predefined type for a field: you can write a custom field that returns object in different types depending on the database value.如果您查看用于将值转换为 python 对象的文档,则字段没有硬预定义类型:您可以编写一个自定义字段,根据数据库值返回不同类型的对象。 The doc of model fields specifies what Python type corresponds to each field type, so you can do this "statically".模型字段的文档指定了每个字段类型对应的 Python 类型,因此您可以“静态地”执行此操作。

But why would you need to know the Python types in advance in order to serialize them?但是为什么需要提前知道 Python 类型才能序列化它们呢? The serialize modules are supposed to do this for you, just throw them the objects you need to serialize.序列化模块应该为您执行此操作,只需将您需要序列化的对象扔给它们即可。 Python is a dynamically typed language. Python 是一种动态类型语言。

An ugly alternative is to check the field's repr():一个丑陋的选择是检查字段的 repr():

if 'DecimalField' in repr(model._meta.get_field(fieldname)):
    return decimal.Decimal
else:
    ...

However, you have to this for all types seperatly.但是,您必须针对所有类型单独进行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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