<p>我建议您创建一个单独的模型<strong><code>Attachment</code></strong>,并通过向<code>Attachment</code>模型添加<code>ForeignKey</code>字段或按所需模型使用<code>ManyToManyField</code>来建立与此模型的关系</p>
<p>使用这种方法,您可以将许多文件添加到所需的模型中</p>
<p>下面是<code>Attachment</code>模型的一个示例:</p>
<pre><code>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
<b>test = models.ForeignKey(Test, on_delete=models.CASCADE)</b>
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, <b>self.test</b>)</code></pre>