如何关联新创建的文件模型

How to associate newly created file model

我有这个代码,

@receiver(post_save, sender=FileAnswer)
def save_category_signals(sender, instance, **kwargs):    
    file_types =  ["image", "image-multiple"]
    file_type = instance.question.form_input_type
    if file_type in file_types:
        image_path = instance.body.path
        image = Image.open(image_path)
        img = image.convert('RGB')
        new_path = image_path.rsplit('.', 1)
        pdf = img.save(f'{new_path[0]}_{instance.id}.pdf', format="PDF")
        # os.remove(image_path)
        
        instance.body = pdf
        instance.save()
    
    # os.remove(image_path) # remove old image

此代码不会将文件关联到模型实例。我看过 django ContentFile 和 File。仍然无法真正理解它,因为示例没有那么有用。

尝试这样的事情你应该使用 InMemoryUploadedFile:

@receiver(post_save, sender=FileAnswer)
def save_category_signals(sender, instance, **kwargs):    
    file_types =  ["image", "image-multiple"]
    file_type = instance.question.form_input_type
    if file_type in file_types:
        image_path = instance.body.path
        new_path = image_path.rsplit('.', 1)
        image = Image.open(image_path)
        image = image.convert('RGB')
        output = io.BytesIO()
        image.save(output, format='PDF')
        output.seek(0)
        pdf = InMemoryUploadedFile(output, 'FileField',
                                   f'{new_path[0]}_{instance.id}.pdf',
                                    'application/pdf',
                                    sys.getsizeof(output), None)
        # os.remove(image_path)
        
        instance.body = pdf
        instance.save()
    
    # os.remove(image_path) # remove old image