带有默认字段的 Django 模型序列化问题 [英] Django model serialization problem with default fields

查看:79
本文介绍了带有默认字段的 Django 模型序列化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用模型中,我使用 IntegerRangeField 字段:

Inside of my app model, I use IntegerRangeField fields:

from django.db import models
from django.contrib.postgres.fields import IntegerRangeField
from django.contrib.postgres.validators import RangeMinValueValidator, RangeMaxValueValidator
from psycopg2.extras import NumericRange


class MyModel(models.Model):
    ...

    field = IntegerRangeField(default=NumericRange(400, 600), validators=[
        RangeMinValueValidator(1),
        RangeMaxValueValidator(1000)
    ])
    ...

<小时>

默认"属性仅在管理面板 UI 中使用,其他任何地方都不需要.


The "default" attributes are used in the admin panel UI only, and are not needed anywhere else.

如果我在迁移后添加它们,它们会顺利运行.但是,如果我在运行 makemigrations 之前添加它们,则会收到以下消息:

If I add them after migration, they work smoothly. However, if I add them before I run makemigrations, I get this message:

ValueError: 无法序列化:NumericRange(400, 600, '[)') 有一些值 Django 无法序列化到迁移文件中.

ValueError: Cannot serialize: NumericRange(400, 600, '[)') There are some values Django cannot serialize into migration files.

我什至不希望将默认值保存到我的 PostgreSQL 数据库中,我只是不想每次运行 makemigrations 时都不必删除它们并将它们带回来.

I don't even want the default values to be saved to my PostgreSQL database, I just want to not have to remove and bring them back every time I run makemigrations.

有什么想法吗?

(不起作用:具有较低"和较高"属性的自定义对象、单个整数、字符串、元组)

(Didn't work: a custom object with "lower" and "higher" attributes, a single integer, a string, a tuple)

Python:3.6.6,Django:2.1.2,PostgreSQL:11.0

Python: 3.6.6, Django: 2.1.2, PostgreSQL: 11.0

推荐答案

尝试将默认值计算移到单独的函数中:

Try to move default value calculation into separate function:

def get_default_range():
    return NumericRange(400, 600)

class MyModel(models.Model):
    field = IntegerRangeField(default=get_default_range, validators=[
        RangeMinValueValidator(1),
        RangeMaxValueValidator(1000)
    ])

在这种情况下,迁移成功生成:

In this case migration was successfully generated:

   operations = [
       migrations.AddField(
            model_name='comment',
            name='field',
            field=django.contrib.postgres.fields.ranges.IntegerRangeField(
                default=play.models.get_default_range,
                validators=[django.contrib.postgres.validators.RangeMinValueValidator(1),
                            django.contrib.postgres.validators.RangeMaxValueValidator(1000)]),
        ),
    ]

这篇关于带有默认字段的 Django 模型序列化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆