Django模型字段可调用默认不起作用

时间:2018-05-10 15:13:32

标签: django django-models django-migrations

Django的可调用模型字段默认值已被破坏。当我将模型字段默认设置为等于可调用时(请参阅下面的迁移文件),即使每次调用时callable返回不同​​的值,所有模型都会获得相同的值。

这适用于以前的领域,所以我很困惑为什么Django会在这个领域失败。一切正常,直到我迁移,检查数据库列显示所有值都相同。

迁移文件:

# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2018-05-10 14:53
from __future__ import unicode_literals

from django.db import migrations, models
import screen.models


class Migration(migrations.Migration):

    dependencies = [
        ('screen', '0064_employer_enable_show_question_template_tags'),
    ]

    operations = [
        migrations.AddField(
            model_name='question',
            name='key',
            field=models.TextField(default=screen.models.generate_question_key),
        ),
    ]

模型

def generate_question_key():
    # return a random string 64 characters long
    return generate_random_hash(64)

class Question(Model):
    name = TextField()
    points = PositiveIntegerField() # how much it's worth
    time_spent = PositiveIntegerField(default = 0) # seconds
    score = PositiveIntegerField(default = 0)
    key = TextField(default = generate_question_key)

默认值返回不同的值:

>>> import screen
>>> screen.models.generate_question_key()
'JpZzloZkiLyvPLrDZ9764VTWkNUon1FD08mGKODa2uiqW1nV422HXVvt78MsW7aR'
>>> screen.models.generate_question_key()
'NHyTwPDA2cAAsTeIR77INLMM6Ik14EQ6vTlrTv4ZwV56nt6jGEtR8bKn8iyWDeMA'
>>> screen.models.generate_question_key()
'q2aALA7WmvtiKLiGXfNEStpKhOFcNpMDrJ8Y9sv6mwWNsUU6mdgMlgaW5yJJ1yEI'
>>> 

1 个答案:

答案 0 :(得分:1)