带有null = True的ForeignKey字段给出' NoneType' object没有属性id

时间:2014-05-21 06:01:32

标签: python django-models

我是Django的新手。

我有以下models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import os

def get_upload_path(instance, filename):
    return os.path.join(
      "folder_%d" % instance.folder.id, filename)

class Folder(models.Model):

    folder_name=models.CharField(max_length=100)
    parent_folder=models.ForeignKey('self', null=True, blank=True)
    folder_description=models.TextField(max_length=200)

        def __unicode__(self):
        return self.folder_name
class File(models.Model):

    folder=models.ForeignKey(Folder, null=True, blank=True)
    uploaded_file=models.FileField(upload_to=get_upload_path)
    pub_date = models.DateTimeField('date published',default=timezone.now())
    tag=models.ManyToManyField(FileTag)
    notes=models.TextField(max_length=200)
    uploader=models.ForeignKey(User)

    def __unicode__(self):
        return str(self.uploaded_file)

def filename(self):
        return os.path.basename(self.uploaded_file.name)

如果我尝试使用null属性保存File对象,则会给出“属性错误”#39;说' NoneType'对象没有属性ID

1 个答案:

答案 0 :(得分:2)

无论如何模型执行这个方法:

def get_upload_path (instance, filename): 
    return os.path.join ("folder_% d"% instance.folder.id, filename) 

试图访问文件夹,但文件夹是NoneType

你需要这样的东西

def get_upload_path (instance, filename): 
    folder = instance.folder and instance.folder.id or 'default'
    return os.path.join ("folder_% d"% folder, filename)