动态文件字段路径
我正在尝试使用 get_file_path
函数来生成动态路径。我可以在 get_file_path
中使用 Album
slug 字段代替此 str(instance.id)
吗?谢谢
这是模型
def get_file_path(instance, filename):
return os.path.join('files', str(instance.id), filename)
class Album(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique = True,max_length=100,help_text="Suggested value automatically generated from name. Must be unique.")
path = models.CharField(max_length=100,null=True, blank=True)
language = models.ForeignKey(Category)
albumid = models.CharField(max_length=100)
class Song(models.Model):
title = models.CharField(max_length=100)
artist = models.ManyToManyField(Artist)
music = models.ForeignKey(Music)
album = models.ForeignKey(Album)
file = models.FileField(upload_to=get_file_path)
更新:我尝试了 instance.slug
。它不起作用。歌曲模型中不存在 instance.slug
。它仅存在于专辑模型中(想要使用 Album
Slug 字段) Update2:这是模型快照
I'm trying to use get_file_path
function to generate dynamic path. Can I use Album
slug field instead of this str(instance.id)
in get_file_path
? thanks
Here is models
def get_file_path(instance, filename):
return os.path.join('files', str(instance.id), filename)
class Album(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique = True,max_length=100,help_text="Suggested value automatically generated from name. Must be unique.")
path = models.CharField(max_length=100,null=True, blank=True)
language = models.ForeignKey(Category)
albumid = models.CharField(max_length=100)
class Song(models.Model):
title = models.CharField(max_length=100)
artist = models.ManyToManyField(Artist)
music = models.ForeignKey(Music)
album = models.ForeignKey(Album)
file = models.FileField(upload_to=get_file_path)
Update: I tried instance.slug
. Its not working. instance.slug
does not exist in Song Model. Its only exists in Album model ( Want to use Album
Slug field)
Update2: Here is model snapshot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
非常简单:
str(instance.album.slug)
Quite straightforward:
str(instance.album.slug)
是的,只需使用
instance.slug
而不是instance.id
您可以在帖子的答案中找到另一个示例 在 Django 中保存文件之前更改文件名
更新:如果不是所有实例都有 slug 字段,那么您可能会有兴趣像这样的解决方案:
Yes, just use
instance.slug
instead ofinstance.id
Another example you can find in the answer of post Change filename before save file in Django
Update: If not all instances have a slug field than you could be interested in a solution like this: