2016-01-20 58 views
2

这是一个游戏mod文件共享站点。我有Apps Mods和Games。每次举行,你猜对了,MODS和游戏!Django FileField根据ForeignKey记录的slug字段生成路径

这里是我的MODS的模型:

from django.db import models 
# Register storage backend TODO 
def mod_directory_path(instance, filename): 
    # file will be uploaded to MEDIA_ROOT/<game>/<filename> 
    # Example code from https://docs.djangoproject.com/en/1.9/ref/models/fields/ 
    return 'user_{0}/{1}'.format(instance.user.id, filename) 

# Create your models here. 
class Mods(models.Model): 
    title = models.CharField(max_length=30) 
    author = models.CharField(max_length=30) 
    game = models.ForeignKey(
     'games.Games', 
     on_delete=models.CASCADE, 
    ) 
    website = models.URLField() 
    repoWebsite = models.URLField() 
    upload = models.FileField(upload_to=mod_directory_path) 

这里是我的游戏模式:

from django.db import models 

# Create your models here. 
class Games(models.Model): 
    title = models.CharField(max_length=30) 
    developer = models.CharField(max_length=30) 
    website = models.URLField() 
    slug = models.SlugField() 

我要自动设置的mod_directory_path到游戏模式的蛞蝓。

例如,如果Mod项目“Dynamic War Sandbox”具有指向Arma 3游戏的唯一ID的ForeignKey,我希望文件上传路径基于Arma 3的数据库条目的段落。

MEDIA_ROOT/arma-3/<filename>. 

我该怎么做?

回答

0

像这样的东西应该工作。唯一的要求是在创建mod之前,游戏已经存在于你的数据库中。

def mod_directory_path(instance, filename): 
    slug = instance.game.slug 
    return os.sep.join([slug, filename]) 
+0

太棒了!如果它在几周内有效,我会测试并报告。这是我从MeteorJS切换后的第一个Django项目。最终,我希望文件路径不仅基于游戏slug而且还基于游戏类别生成,例如:MEDIA_ROOT/arma-3/addons/models/。这是完全不同的怪物,因为我需要弄清楚如何根据游戏类别字段中包含的数组进行分类。 – zorrobyte