首页 > 解决方案 > AttributeError:模块没有属性

问题描述

当我尝试将 auth_code(模型类中的变量)中使用的函数名称“random_string”更改为任何其他名称时,它会在命令行中显示错误:AttributeError: module 'users_data.models' has no attribute 'random_string'

from django.db import models
from django.utils.timezone import now
import random
from django.core.exceptions import ValidationError


def random_string():
    return int(random.randint(000000, 999999))


def validate_phone_number(phone):
    if len(phone) < 7:
        raise ValidationError('Phone number can not be less than 7 digits')


class Users(models.Model):
    phone = models.CharField(verbose_name='Phone', max_length=20, validators= 
                            [validate_phone_number])
    auth_code = models.IntegerField(verbose_name='Code', 
                                    default=random_string)
    get_in_date = models.DateTimeField(default=now, blank=False, 
                                       editable=False)

我看过很多帖子涵盖了我的问题,但我没有发现任何有用的东西。我将不胜感激任何帮助。

标签: pythondjangodjango-modelsdjango-rest-framework

解决方案


问题出在您的迁移文件中,如本期所示。基本上,当您生成以前的迁移文件时,会写入字段的默认值是random_string.

现在,如果您更改该函数名称,您当前的代码将起作用,但由于您已经生成的迁移文件使用此函数,它们将引发错误,因为它们无法再找到该函数。

我不知道仅更新文件以替换其中的名称是否就足够了。其他解决方案是重置迁移(尽管这可能会产生成本)。

我提供的链接提供了一个脚本来解决这个问题,但我自己没有测试过


推荐阅读