我有项目模型
class Project(models.Model):
id = models.UUIDField(primary_key=True, unique=True, default=uuid4, editable=False)
logo = models.ImageField(validators=[validate_image_size], blank=True, null=True, default=None)
name = models.CharField(max_length=64)
description = models.TextField()
@transaction.atomic
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def __str__(self):
return self.name
我想压缩徽标字段与接收器
@receiver(post_save, sender=Project)
def compress_project_logo(sender, instance, **kwargs):
compress_image.apply_async((instance.id,))
使用共享任务
@shared_task
def compress_image(project_id):
from api.models import Project
project = get_object_or_404(Project, id=project_id)
compressed_image = Image.open(project.logo)
compressed_image = compressed_image.convert("RGB")
compressed_image = ImageOps.exif_transpose(compressed_image)
image_io = BytesIO()
compressed_image.save(image_io, "JPEG", quality=70)
project.logo = InMemoryUploadedFile(image_io, "ImageField", project.logo.file.name, "image/jpeg", sys.getsizeof(image_io), None)
project.save()
当我通过django管理员保存项目模型时,我把这个
Traceback (most recent call last):
2023-02-28 10:27:45
File "/usr/local/lib/python3.8/site-packages/celery/app/trace.py", line 450, in trace_task
R = retval = fun(\*args, \*\*kwargs)
File "/usr/local/lib/python3.8/site-packages/celery/app/trace.py", line 731, in __protected_call__
return self.run(\*args, \*\*kwargs)
File "/code/api/tasks/compress.py", line 14, in compress_image
project = get_object_or_404(Project, id=project_id)
File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 19, in get_object_or_404
return \_get_object_or_404(queryset, \*filter_args, \*\*filter_kwargs)
File "/usr/local/lib/python3.8/site-packages/django/shortcuts.py", line 78, in get_object_or_404
raise Http404('No %s matches the given query.' % queryset.model.\_meta.object_name)
django.http.response.Http404: No Project matches the given query.
1条答案
按热度按时间ktecyv1j1#
我认为应该在
save
方法上删除transaction.atomicdecorator