2 回答

TA貢獻1815條經驗 獲得超10個贊
您可以像這樣向模型添加屬性,請注意我在字段名稱中添加了下劃線:
class Content(models.Model):
...
_avatar = models.ImageField(upload_to=file, blank=True, null=True)
@property
def avatar(self):
return self._avatar.url
現在你可以這樣做:
print(content.avatar)

TA貢獻1827條經驗 獲得超8個贊
使用__str__()方法
class Content(models.Model):
...
avatar = models.ImageField(upload_to=file, blank=True, null=True)
def __str__(self):
try:
return self.avatar.url
except AttributeError: # "self.avatar" may be None
return "no avatar"
更新-1
我想,@propert可能適合你
class Content(models.Model):
...
avatar = models.ImageField(upload_to=file, blank=True, null=True)
@property
def avatar_url(self):
try:
return self.avatar.url
except AttributeError: # "self.avatar" may be None
return "no avatar"
現在,您可以訪問該網址,
print(content.avatar_url)
添加回答
舉報