检查模型是否具有特定属性,是否找到了该属性,请检查其是否具有值



我有2个Django型号,非常相似:

class ImageUp(models.mode)l:
    image = models.ImageField(upload_to=file_upload_to)
    additional_image_types = JSONField(null=True, blank=True)
    filename = models.CharField(max_length=255, blank=True, null=True)

class LogoUp(models.model):
    logo = models.ImageField(upload_to=file_upload_to)
    additional_logo_types = JSONField(null=True, blank=True)
    filename = models.CharField(max_length=255, blank=True, null=True)

i从数据库中检索模型的实例,我想进行一些映像/徽标操作,因此我正在检查属性是否存在:

try:      
    additional = obj.getattr( f'additional_{attr_name}_types')
except AttributeError:
   .....

attr_name,我作为参数收到,可以是'徽标'或'image' additional_..,可以为null,json空或具有值的json

我收到2个错误:

  object has no attribute 'getattr'
  getattr(): attribute name must be string # if I check type of `f string` is <str>

所以,我想要的是知道它是和image还是logo,如果addtional..有值

getattr不是对象上的方法;这是一个内置功能。您需要:

additional = getattr(obj, f'additional_{attr_name}_types')

(它是通过__getattr__方法实现的,但您不应该直接调用双键入方法。)

最新更新