简体   繁体   English

使用 Django Model 将文件保存到 JSONField

[英]Save file with Django Model to JSONField

I need to save files, but the number of files is uncertain, and in one request I can add a file, then in another request post, I can add one more file...我需要保存文件,但是文件数量不确定,在一个请求中我可以添加一个文件,然后在另一个请求帖子中,我可以再添加一个文件...

For this reason I thought that creating a JSONField type field could help me in this matter, but I don't know if it is possible and if it is possible I have no idea how to implement it in Django.出于这个原因,我认为创建一个 JSONField 类型的字段可以帮助我解决这个问题,但我不知道这是否可能,如果可能的话,我不知道如何在 Django 中实现它。

Here is an example of how I currently upload a single file to Django Model:这是我当前如何将单个文件上传到 Django Model 的示例:

import uuid
import time

from users.models import User
from django.db import models


def upload_location(instance, filename):
    filebase, extension = filename.split('.')
    milliseconds = int(round(time.time() * 1000))

    return 'events/thumbnail_images/%s__%s__%s.%s' % (instance.user_id, instance.name, milliseconds, extension)


class Test(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
    image_link = models.FileField(upload_to=upload_location)

    user = models.ForeignKey(
        User,
        null=True,
        blank=False,
        on_delete=models.CASCADE
    )

As I'm using Postgres relational database, and I'm not sure how many files the user will want to save, I figured using JSONField, so that as the user adds files, the 'path+filename' is also added.由于我使用的是 Postgres 关系数据库,并且我不确定用户要保存多少文件,所以我想使用 JSONField,这样当用户添加文件时,也会添加“路径+文件名”。

It's possible?这是可能的? How to make?怎么做?

I suggest you to create a separate model Attachment and make the relation with this model by adding ForeignKey field To Attachment model or using ManyToManyField by desired model. I suggest you to create a separate model Attachment and make the relation with this model by adding ForeignKey field To Attachment model or using ManyToManyField by desired model.

With this approach you can add many files to the desired model.使用这种方法,您可以将许多文件添加到所需的 model。

Here is an example of Attachment model:以下是Attachment model 的示例:

import uuid
import time

from users.models import User
from django.db import models


def upload_location(instance, filename):
    filebase, extension = filename.split('.')
    milliseconds = int(round(time.time() * 1000))

    return 'events/thumbnail_images/%s__%s__%s.%s' % (instance.user_id, instance.name, milliseconds, extension)


class Test(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
    user = models.ForeignKey(User,null=True,blank=False,on_delete=models.CASCADE)


class Attachment(models.Model):
    # here is the relation
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    name = models.CharField(verbose_name="Attachment Name", max_length=255, null=True, blank=True)
    att_img = models.ImageField(
        upload_to=upload_location,
        verbose_name="Attach an Image",
        null=True, blank=True, max_length=255
    )
    att_file = models.FileField(
        upload_to=upload_location,
        verbose_name="Attach a File",
        null=True, blank=True, max_length=255
    )
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.name, self.test)

For file i am just taking image as an example对于文件,我只是以图像为例

  class ImageClass(models.Model):
  YourClassHere_FK_image  = models.ForeignKey(
        'YourClassHere', related_name='images', on_delete=models.CASCADE)
    title = models.CharField(max_length=200, blank=True)
    image = models.ImageField(upload_to=UploadedConfigPath_image, verbose_name='Image', null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=[
                              'jpg', 'png',  'jpeg', 'webp'])], help_text="Something related images")

Then in your forms.py file do something like this然后在你的 forms.py 文件中做这样的事情

class Mult_ImageForm(forms.Form):
multiple_images = forms.FileField(required=False, help_text='Select Multiple Images(jpg,png) for your Class if you want (Optional) Max:10',
                                  widget=forms.ClearableFileInput(attrs={'multiple': True, 'accept': 'image/*'}))

Then do the views.py然后做views.py

def post_create(request):

    mul_images_product      =       Mult_ImageForm(request.POST,request.FILES)


    if request.method == 'POST':
    Your code here

Also in your HTML you need to render this form as you said it could be requested again and again.同样在您的 HTML 中,您需要呈现此表单,因为您说可以一次又一次地请求它。 This is the simplest way to do it as per my understanding.根据我的理解,这是最简单的方法。 You can add as many files as you like just provide them same foreign key to your ImageClass model in your views:)您可以添加任意数量的文件,只需在您的视图中为您的 ImageClass model 提供相同的外键即可:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM