python - 在 Django 中使用 JSONField 的默认字典列表

标签 python django django-rest-framework

Django 2.0、Django-Rest-Framework 3.8、Python 3.6

我正在使用 Postgres 数据库并尝试将以下内容设置为 JSONField 的默认值:

from django.db import models
from django.contrib.postgres.fields import JSONField

class TrainerProfile(models.Model):
    """data required to pull up trainer profile"""

    specific_workouts = JSONField(default=[{"specific": "standard session", "price": 100.00, "units": 1, "hours_per_unit": 1}, {"specific": "standard session", "price": 250.00, "units": 3, "hours_per_unit": 1}, {"specific": "standard session", "price": 300.00, "units": 5, "hours_per_unit": 1}])

    def __str__(self):
        return str(self.specific_workouts)

在 Django 文档中,它是这样写的:

If you give the field a default, ensure it’s a callable such as dict (for an empty default) or a callable that returns a dict (such as a function). Incorrectly using default={} creates a mutable default that is shared between all instances of JSONField.

我想提供一个列表包含默认的字典。我可以通过原始数据或 Django Rest Framework 中的可浏览 api 发布字典列表,但我需要知道如何默认设置它。我希望它将此作为默认值发布:

"specific_workouts": [
            {
                "price": 100.0,
                "units": 1,
                "specific": "standard session",
                "hours_per_unit": 1
            },
            {
                "price": 250.0,
                "units": 3,
                "specific": "standard session",
                "hours_per_unit": 1
            },
            {
                "price": 300.0,
                "units": 5,
                "specific": "standard session",
                "hours_per_unit": 1
            }
        ]

我猜我必须覆盖 save() 才能执行此操作,但我不确定如何实际实现它。非常感谢任何帮助。


更新

我已尝试执行以下操作,但仍返回一个空值作为默认值。

from django.db import models
from django.contrib.postgres.fields import JSONField

def default_specific_workouts():
    return [
        {
            "price": 100.0,
            "units": 1,
            "specific": "standard session",
            "hours_per_unit": 1
        },
        {
            "price": 250.0,
            "units": 3,
            "specific": "standard session",
            "hours_per_unit": 1
        },
        {
            "price": 300.0,
            "units": 5,
            "specific": "standard session",
            "hours_per_unit": 1
        }
    ]

class TrainerProfile(models.Model):
    """data required to pull up trainer profile"""

    specific_workouts = JSONField(default=default_specific_workouts)

    def __str__(self):
        return str(self.specific_workouts)

也值得一提 即使我输入:

specific_workouts = JSONField(default=list)

specific_workouts = JSONField(default=dict)

真的不确定如何从这里开始。

最佳答案

如您引用的摘录中所述,您可以使用任何可调用对象作为默认值。因此,您可以创建自己的方法来调用以创建默认值。

def default_specific_workouts():
    # You probably want this in a variable, just copy/pasting your sample data
    # to keep the example simple
    return [
        {
            "price": 100.0,
            "units": 1,
            "specific": "standard session",
            "hours_per_unit": 1
        },
        {
            "price": 250.0,
            "units": 3,
            "specific": "standard session",
            "hours_per_unit": 1
        },
        {
            "price": 300.0,
            "units": 5,
            "specific": "standard session",
            "hours_per_unit": 1
        }
    ]

现在你可以这样做了:

specific_workouts = JSONField(default=default_specific_workouts)

关于python - 在 Django 中使用 JSONField 的默认字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51972734/

相关文章:

python - 扭曲的海螺,压倒一切的认证

python - 导入错误 : cannot import name 'bigquery_storage_v1beta1' from 'google.cloud' (unknown location)

python - 当字段变化时如何调用类模型中的函数?

javascript - iPad 不使用 javascript 更新页面(使用 Django 后端)

python - Django-rest-framework @detail_route 用于特定网址

python - 如何在 snakemake 输出中执行简单的字符串操作

django - 用于授权和身份验证的 Oauth2?

python - 如何在基于类的通用 View 中使用分页?

python - Django Rest 框架中的 get_FIELD_serializer

python - 如何验证 DRF (Django Rest Framework) generic.ListView 中的 url 变量?