【发布时间】:2009-10-15 00:27:59
【问题描述】:
在我的 UserProfile 模型中,我希望有一个函数,它返回 either 用户的 ImageFileField 对象或默认图像(如果用户尚未上传自己的图像)。
例如:
class UserProfile(models.Model):
pic = models.ImageField('Headshot',blank=True,
upload_to=get_path_and_filename)
def get_pic(self):
if self.pic:
return self.pic
else:
# return ImageFileField with a default value
我想返回一个等效的ImageFileField,因为我有适用于这种对象类型的过滤器(所以我不能轻易地传递一个字符串)...我尝试查看source code,但我可以不太清楚自己该怎么做。
有没有一种简单的方法来初始化一个新的ImageFileField 对象,方法是向它传递一个图像文件的路径,然后返回它?
PS:我曾考虑为 ImageField 使用 default 设置,但是,它似乎不太灵活,因为文件存储在模型创建时......如果我以后想更改默认文件,我必须更新所有具有旧文件的数据库条目。
【问题讨论】:
标签: django django-models