我非常喜欢get_or_create()
和update_or_create()
方法。
他们似乎与FileField不兼容。
如果我尝试这样做:
blob, created = Blob.objects.get_or_create(name='foo2',
defaults=dict(content_file='my_content'))
...我得到:
/home/u/bin/python /home/u/src/test-filefield-get-or-create.py
Traceback (most recent call last):
File "/home/u/src/test-filefield-get-or-create.py", line 7, in <module>
print(blob.content_new.read())
File "/home/u/src/modlink/modlink/models/blob.py", line 65, in _get_content
self._cached_content = self.content_file.read()
File "/home/u/lib/python2.7/site-packages/django/core/files/utils.py", line 16, in <lambda>
read = property(lambda self: self.file.read)
File "/home/u/lib/python2.7/site-packages/django/db/models/fields/files.py", line 51, in _get_file
self._file = self.storage.open(self.name, 'rb')
File "/home/u/lib/python2.7/site-packages/django/core/files/storage.py", line 38, in open
return self._open(name, mode)
File "/home/u/lib/python2.7/site-packages/minio_storage/storage.py", line 106, in _open
"File {} could not be saved: {}".format(name, str(e)), e)
minio_storage.errors.MinIOError: File x could not be saved: NoSuchKey: message: The specified key does not exist.
我的模特:
class Blob(models.Model):
content_file = models.FileField(null=True)
name = models.CharField(max_length=10000, default='')
如果我尝试这样做:
import django
from django.core.files.base import ContentFile
django.setup()
from modlink.models import Blob
blob = Blob.objects.create(content_file=ContentFile('x'))
print(blob.content_file.read())
我明白了:
Traceback (most recent call last):
File "/home/u/src/test-filefield-get-or-create.py", line 9, in <module>
print(blob.content_file.read())
File "/home/u/local/lib/python2.7/site-packages/django/core/files/utils.py", line 16, in <lambda>
read = property(lambda self: self.file.read)
File "/home/u/local/lib/python2.7/site-packages/django/db/models/fields/files.py", line 49, in _get_file
self._require_file()
File "/home/u/local/lib/python2.7/site-packages/django/db/models/fields/files.py", line 46, in _require_file
raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
ValueError: The 'content_file' attribute has no file associated with it.
仅作记录,我认为如果您可以像其他数据类型一样在create(),get_or_create()和update_or_create()中使用二进制数据,那就太好了。这将需要一个“ NamelessFileField”。我在这里写下了我的想法:https://groups.google.com/forum/#!topic/django-users/7UmFbIg4aE8