【问题标题】:Retrieving the name of the class which powers a model field检索为模型字段提供支持的类的名称
【发布时间】:2013-03-06 23:38:06
【问题描述】:

我正在处理一些 django 代码中的一些边缘情况,我遇到了一个只有在涉及特定字段时才会遇到的问题。

我希望能够检测模型用于字段的类,并根据结果放入备用逻辑。

我尝试在字段实例上使用get_internal_type(),但它只返回"BooleanField",而不是预期的"ModifiedField"

自定义字段类型:

class ModifiedField(models.BooleanField):
    def __init__(self, *args, **kwargs):
        kwargs['editable'] = False
        models.BooleanField.__init__(self, *args, **kwargs)

    def pre_save(self, model_instance, add):
        value = getattr(model_instance, self.attname)

        if add:
            return True
        elif value == 2:
            return False
        else:
            return True

型号:

class TemplateItem(models.Model):
    uuid = UUIDField(primary_key=True)
    name = models.CharField(null=False, blank=True, max_length=255)
    image = models.ImageField(_('Image'), upload_to=_template_image_upload_path,
                              storage=item_fs, null=True, blank=True)
    is_modified = ModifiedField()

【问题讨论】:

    标签: django django-1.3


    【解决方案1】:

    你尝试过class._name_ ??

    g = TemplateItem.objects.get(id=1)
    g.__class__.__name__
    

    【讨论】:

    • 其实 op 是在寻找模型的 field 类,而不是模型本身的类。
    • 谢谢你,我现在觉得有点愚蠢,因为我不记得我能做到这一点!
    • @brunodesthuilliers 是对的,我确实想要字段类,但是如果您像我一样有该类的实例,那么只需调用instance.__class__.__name__
    【解决方案2】:
    fld_cls = type(model_instance._meta.get_field(fieldname))
    

    【讨论】:

      猜你喜欢
      • 2019-11-13
      • 2013-02-12
      • 2019-02-03
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多