gpt4 book ai didi

python - null=True 的ForeignKey 字段给出 'NoneType' 对象没有属性id

转载 作者:行者123 更新时间:2023-12-01 05:13:12 27 4
gpt4 key购买 nike

我是 Django 新手。

我有以下模型.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 文件夹属性的文件对象,它会给我“AttributeError”,说“NoneType”对象没有属性 ID

最佳答案

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

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)

关于python - null=True 的ForeignKey 字段给出 'NoneType' 对象没有属性id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23775134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com