【问题标题】:Insert data in model from json in django从 django 中的 json 向模型中插入数据
【发布时间】:2020-07-23 00:10:57
【问题描述】:

我的模特:

class Post_Data(models.Model):
    id = models.AutoField(primary_key=True)
    data = models.CharField(max_length=200)

我需要在模型中插入json数据,在邮递员中以“文件​​”的形式传递。

我试过了:

    def post(self, request):
        json_file = request.FILES['json_file']
        with open(json_file) as f:
            json_data = json.loads(f)
            a = Post_data(data=json_data)
            a.save()

但它不起作用。

【问题讨论】:

    标签: python json django django-models django-views


    【解决方案1】:

    您是否查看过 Django Fixtures 的数据预填充。此外,使用 JsonField() 可能对您有用。

    from django.contrib.postgres.fields import JSONField
    
    class ......
        data = JSONField()
    

    【讨论】:

    • 我正在尝试通过文件发送数据,即通过在请求中请求文件而不是存储在模型中。 @DARK_C0D3R
    • 可以打印json_data的类型和数据吗
    • 打印(类型(json_data))
    • 我在上传文件时收到无效文件: 错误。
    • 您可能正在从某个缓冲区读取它,这可能很有用stackoverflow.com/a/59438263/8865579
    猜你喜欢
    • 1970-01-01
    • 2014-06-24
    • 2016-02-28
    • 2015-05-09
    • 2014-09-08
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多