检查模型是否具有特定属性,如果找到,则检查其是否具有值

时间:2019-02-21 08:54:38

标签: python django python-3.x django-models

我有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)

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

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

attr_name,我将其作为参数接收,可以是“徽标”或“图像”,但是我仍然进行检查,以防发送了错误的“前缀”  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>

因此,我想知道的是imagelogo(如果addtional..具有值)

1 个答案:

答案 0 :(得分:2)

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

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

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

相关问题