访问ForeignKey属性

时间:2011-08-02 21:40:38

标签: django django-models django-admin

我有两个型号。基本上,我正在讨论这个问题:Multiple images per Model我想得到Design模型的machine_name的值,并在DesignImage模型中为ImageField upload_to创建路径时使用它。效果如下:image = models.ImageField(upload_to='designs/' + design.get_machine_name + '/images')

这会产生以下错误:AttributeError: 'ForeignKey' object has no attribute 'get_machine_name'

我希望下面的代码清楚。

from django.db import models
from django.db.models.fields.related import ManyToManyField
from django.template.defaultfilters import slugify

class Design(models.Model):
    name = models.CharField(max_length=30, help_text='Name of the design.')
    machine_name = models.SlugField(editable=False)

    def save(self, *args, **kwargs):
        self.machine_name = slugify(self.name)
        super(Design, self).save(*args, **kwargs)

    def get_machine_name(self):
        return self.machine_name

    def __unicode__(self):
        return self.name

class DesignImage(models.Model):

    def get_upload_dir(self):
        return 'designs/' + self.design.machine_name + '/images'

    design = models.ForeignKey(Design, related_name='images')
    caption = models.CharField(max_length=100)
    image = models.ImageField(upload_to='designs/' + design.get_machine_name + '/images')

    def __unicode__(self):
        return self.caption

我已经包含以下代码,以防它可能有用:

from designs.models import *
from django.contrib import admin

class DesignImageInline(admin.TabularInline):
    model = DesignImage
    extra = 3 # number of extra inline form fields to display

class DesignAdmin(admin.ModelAdmin): 
    inlines = [ DesignImageInline, ]

admin.site.register(Design, DesignAdmin)
admin.site.register(DesignImage)

2 个答案:

答案 0 :(得分:2)

如果上传ImageField的位置取决于实例(如此处所示),upload_to参数可以是可调用的而不是字符串,在该字符串中将传递当前实例和文件名。你需要这样的东西:

import os 

def upload_to(instance, filename):
    return os.path.join('designs', instance.design.machine_name, 'images', filename)

...
    image = models.ImageField(upload_to=upload_to)

答案 1 :(得分:1)

问题出在这一行:

image = models.ImageField(upload_to ='designs /'+ design.get_machine_name +'/ images')

字段设计未在“编译时”定义,它是模型中的另一个字段。

您需要在运行时将其应用于您用于编辑的每种形式。