【发布时间】:2022-01-18 11:34:26
【问题描述】:
我的用户模型中有一个字段仅用于特定类型的用户
student_id = models.CharField(_("student id"), validators=[
MinValueValidator(10_000_000_000),
MaxValueValidator(99_999_999_999)
],unique=True, max_length=8, blank=True, null=True)
在 serializers.py 文件中创建用户时,我尝试了以下代码,但没有成功
def create(self, validated_data):
def create_new_ref_number():
not_unique = True
while not_unique:
unique_id = randint(10000000, 99999999)
if not User.objects.filter(student_id=unique_id):
not_unique = False
instance = User.objects.create(
student_id=create_new_ref_number,
firstname=validated_data['firstname'],
middlename=validated_data['middlename'],
lastname=validated_data['lastname'],
age=validated_data['age'],
phone=validated_data['phone'],
)
保存用户后,student_id 字段将填充以下字符串
<function RegisterSerializerStudent.create.<locals>.create_new_ref_number at 0x000001E4C463A950>
【问题讨论】:
标签: django django-rest-framework