包含图像、文件和标签的模型的夹具数据

Fixtures data for model containing images, files and tags

我正在使用 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 灯具文件中指定文件?

如果您尝试通过 admin 界面保存带有图像的 Post,例如 image.png,然后查看数据库,您会发现 post' s 图像以其相对路径保存: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",
      }
    }
]