你好,
我刚刚创建了两个模型:
models.py
from django.db import models
from django.contrib.auth.models import User
import uuid
from uuid_upload_path import upload_to
from django.core.exceptions import ValidationError
from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
class StorageObject(models.Model):
name = models.CharField(max_length=200)
text = models.TextField(blank=True)
slug = models.UUIDField(default=uuid.uuid4)
display = models.BooleanField(default=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
# types
file = models.FileField(upload_to=upload_to, blank=True, null=True)
image = models.ImageField(upload_to=upload_to, blank=True, null=True)
link = models.URLField(blank=True)
@cached_property
def file_type(self):
if self.file:
return 1
elif self.image:
return 2
elif self.link:
return 3
def clean(self):
if self.file and (self.image or self.link):
raise ValidationError(_('Storage Objects can only contain one storage type each'))
elif self.image and (self.link or self.file):
raise ValidationError(_('Storage Objects can only contain one storage type each'))
elif self.link and (self.file or self.image):
raise ValidationError(_('Storage Objects can only contain one storage type each'))
if not (self.link or self.image or self.file):
raise ValidationError(_('Storage Objects must contain exactly one storage type'))
def __str__(self):
return '%s (by %s)' % (self.name, self.owner)
class Collection(models.Model):
name = models.CharField(max_length=200)
active = models.BooleanField(default=True)
objects = models.ManyToManyField(StorageObject)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
正如标题所述,每当我尝试通过管理界面创建AttributeError
时,都会得到Collection
。
但是,创建StorageObject
可以很好地工作并且可以正确清理。
我搜索了此消息,大多数人似乎忘记了某个地方的实例括号(如StorageObject())。也许我是盲人,但我找不到错误。
所以我继续删除了自定义函数file_type
和clean
,但结果仍然相同。
我在这里想念什么?谢谢您的宝贵时间!
堆栈
File "C:\Users\[..]\venv\lib\site-packages\django\db\models\manager.py", line 176, in __get__
raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__)
AttributeError: Manager isn't accessible via Collection instances
答案 0 :(得分:1)
请勿在模型上添加字段objects
,这与也称为Manager
的模型objects
冲突。除非您决定给它起一个不同的名称(请参见here),否则Collection.objects
应该返回一个Manager
。