默认情况下,一次更新数千条记录具有挑战性。
一个问题是数据库方面的性能。我能想到的最好的方法是使用update
和覆盖一些方法。假设您已经在某个目录中有图像。
from django.db.models import fields
from django.db.models import F
from django.db.models.expressions import Value , CombinedExpression
from django.db.models import QuerySet
class TextValue(Value):
def as_sql(self, compiler, connection):
connection.ops.check_expression_support(self)
return '%s', [self.value]
class Expr(F):
ADD = '||' # standard concat row value + value in PostgreSQL
#overwrite method to support text
def _combine(self, other, connector, reversed):
if not hasattr(other, 'resolve_expression'):
other = TextValue(other, output_field=fields.CharField())
return CombinedExpression(self, connector, other)
class Entry(models.Model):
name = models.CharField(unique=True, max_length=200, db_index=True)
image = models.ImageField(upload_to= 'media/' , null=True, blank=True , default='default.png')
现在有了这段代码,您可以批量更新
entries= Entry.objects.all()
entries.update(**{'image': Expr('name') + '.png'})
这样做最好的部分是性能。这是唯一执行的查询
{'sql': 'UPDATE "entry" SET "image" = ("entry"."name" || \'.png\')', 'time': '0.024'}]
更新
做与管理员相同的事情,并为每个条目保存一个模型实例。
from django.contrib import admin
from django import forms
class EntryForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.fields['image'].widget.attrs.update(
{'multiple': True, 'accept': 'image/jpg,image/png,image/gif', })
class EntryAdmin(admin.ModelAdmin):
form = EntryForm
def save_model(self, request, obj, form, change):
files = request.FILES.getlist('image')
# if image exist
if files:
for image_field in files:
try:
instance = Entry.objects.get(name=image_field.name[:-4])
instance.image = image_field
instance.save()
except Entry.DoesNotExist:
pass
else:
return super().save_model(request, obj, form, change)
admin.site.register(Entry , EntryAdmin)
你可以混合这两个部分来获得击球手的表现