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文档中,其内容为:
如果为该字段提供默认值,请确保它是可调用的,例如dict (用于空默认值)或返回dict的可调用对象(例如 功能)。错误地使用default = {}会创建可变的默认值 在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)
也值得一提 即使输入,我仍然返回null:
specific_workouts = JSONField(default=list)
或
specific_workouts = JSONField(default=dict)
真的不确定如何从这里继续。
答案 0 :(得分:2)
如您引用的摘录中所述,可以将任何可调用项用作默认值。这样,您可以创建自己的方法来调用以创建默认值。
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)