这听起来像是一个重复,但我绝对找不到人与我的问题重复。你知道吗
我的型号:
class SuperCoolModel(models.Model):
large = models.ImageField()
small = models.ImageField()
blah = some.OtherClass() # Not a Field type, but is a subclass of ImageFile
我想做的是对这个模型的一个实例的属性进行“迭代”(以某种方式),并对ImageField的一个实例的属性做一些事情。你知道吗
例如,这是一个有效的代码:
from django.db.models.fields.files import ImageFile
a = SuperCoolModel.objects.get(pk=1)
for attrname in dir(a):
# Ignore attr names that we obviously don't care about:
# E.g., anything that starts with an underscore-or-two:
if attrname.startswith('_'):
continue
try:
if isinstance(getattr(a, attrname), ImageFile):
field = getattr(a, attrname)
# Manipulate some stuff, based on the file,
# e.g., using `field.path`.
pass
except AttributeError as e:
# Hopefully this is JUST the 'objects' reference?
pass
在上面的示例中,当它遍历方法/属性名称时,当它到达“object”时,它将引发:
File "<console>", line 3, in <module> File "/path/to/lib/python2.7/site-packages/django/db/models/manager.py", line 206, in __get__
raise AttributeError("Manager isn't accessible via %s instances" % type.__name__)
AttributeError: Manager isn't accessible via SuperCoolModel instances
。。。所以我开始关注AttributeError
异常。或者,我可以在循环中硬编码“objects”,就像我在检查下划线名称时所做的那样。你知道吗
我不能使用a._meta.fields
、a._meta.get_all_field_names()
等,因为我还试图检查一些任意属性的类型,这些属性不是字段,而是某个子类和/或类型的。你知道吗
我这样做是对的,还是有更好的方法跳过这里的“对象”(和其他潜在的“陷阱”)呢?你知道吗
我不理解您为什么不能使用
_meta
方法的解释:您可以使用a._meta.get_all_field_names()
来获得实际字段的列表,然后将任意属性添加到结果列表中。你知道吗在即将发布的1.8版本中,这一点已被弃用,您需要使用
[f.name for f in a._meta.get_fields()]
请注意,none属性将是ImageField的实例。实例没有ImageFields(或CharFields,或任何字段)作为属性;它有实际的字符串、int等,对于图像它使用FieldFile。你知道吗
相关问题 更多 >
编程相关推荐