【问题标题】: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 设备文件中指定文件?

【问题讨论】:

    标签: django django-models django-taggit django-fixtures easy-thumbnails


    【解决方案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",
          }
        }
    ]
    

    【讨论】:

    猜你喜欢
    • 2019-03-05
    • 2014-01-03
    • 2020-10-14
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 2015-04-24
    • 2013-12-23
    • 2021-12-07
    相关资源
    最近更新 更多