包含图像、文件和标签的模型的夹具数据
Posted
技术标签:
【中文标题】包含图像、文件和标签的模型的夹具数据【英文标题】:Fixtures data for model containing images, files and tags 【发布时间】:2021-02-21 15:52:52 【问题描述】:我正在使用 Djano 3.1、Python 3.6、easy-thumbnails 2.7 和 django-taggit 1.3
我想为我的模型创建一个夹具数据文件。
这是我的(简化的)模型:
myapp/models.py
class Post(models.Model):
featured_image = ThumbnailerImageField(upload_to='uploads/post/featured_image', blank=True, null=True)
content = models.CharField(max_text=1000, null=False, blank=False)
tags = TaggableManager()
class PostFileAttachment(models.Model):
post = models.ForeignKey(Post, related_name='attachments', on_delete = mFixtures data for model containing images and filesodels.CASCADE)
file = models.FileField(upload_to="uploads/post/attachments")
class PostImageGallery(models.Model):
post = models.ForeignKey(Post, related_name='pictures', on_delete = models.CASCADE)
description = models.CharField(max_length=100, blank=True, null=True, default='')
image = models.ImageField(upload_to='uploads/blogpost/gallery')
myapp/fixtures/sample_data.json
[
"model": "myapp.Post",
"pk": 1,
"fields":
"featured_image": ???
"content": "This is where the content goes"
"tags": ???
,
"model": "myapp.PostFileAttachment",
"pk": 1,
"fields":
"post": 1
"file": ???
,
"model": "myapp.PostImageGallery",
"pk": 1,
"fields":
"post": 1
"description": "File description",
"image": ???
]
如何在我的 JSON 设备文件中指定文件?
【问题讨论】:
【参考方案1】:如果您尝试通过admin
接口保存Post
与图像,例如image.png
,然后您查看数据库,您会发现帖子的图像是以其相对路径保存的:uploads/post/featured_image/image.png
,所以在您的夹具中,您需要指定该路径。
在您的 myapp/fixtures/sample_data.json
夹具文件中应该是这样的
[
"model": "myapp.Post",
"pk": 1,
"fields":
"featured_image": "uploads/post/featured_image/FEATURED_IMAGE.EXT",
"content": "This is where the content goes",
,
"model": "myapp.PostFileAttachment",
"pk": 1,
"fields":
"post": 1,
"file": "uploads/post/attachments/ATTACHMENT.EXT",
,
"model": "myapp.PostImageGallery",
"pk": 1,
"fields":
"post": 1,
"description": "File description",
"image": "uploads/blogpost/gallery/IMAGE.EXT",
]
【讨论】:
这只是将文件名的字符串加载到数据库中 fixtures 用于预填充数据库 (docs.djangoproject.com/en/3.1/howto/initial-data),然后可以手动移动文件,甚至可以使用自定义命令更好地移动文件。 看看这个包它可能有用pypi.org/project/django-media-fixtures以上是关于包含图像、文件和标签的模型的夹具数据的主要内容,如果未能解决你的问题,请参考以下文章