我使用的是Djano 3.1,Python 3.6,easy-thumbnails 2.7和django-taggit 1.3
我想为我的模型创建一个fixtures数据文件。
以下是我的(简化)模型:
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 fixtures文件中指定文件?
发布于 2020-11-10 02:05:38
如果您尝试通过admin接口将Post与图像一起保存,例如image.png,然后查看数据库,您会发现帖子的图像是以其相对路径uploads/post/featured_image/image.png保存的,因此您需要在fixture中指定该路径。
在您的myapp/fixtures/sample_data.json fixture文件中,它应该如下所示
[
{
"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",
}
}
]https://stackoverflow.com/questions/64756542
复制相似问题