如何遵循警告?
models.py

from django.contrib.postgres.fields import JSONField
from django.db import models
from django_extensions.db.models import TimeStampedModel


class UnderwritingValidator(TimeStampedModel):
    plan = models.PositiveIntegerField(null=True, blank=True, unique=True)
    logic = JSONField(default=dict(
        accept_list=[],
        reject_list=[]
    ))

然后makemigrations
WARNINGS:
uw_validators.UnderwritingValidator.logic: (postgres.E003) JSONField default should be a callable instead of an instance so that it's not shared between all field instances.
    HINT: Use a callable instead, e.g., use `dict` instead of `{}`.
Migrations for 'uw_validators':
  uw_validators/migrations/0002_auto_20191011_0321.py
    - Remove field accept_list from underwritingvalidator
    - Remove field reject_list from underwritingvalidator
    - Add field logic to underwritingvalidator

软件:

zip :10.9
姜戈==2.2.5

问题:
  • 我不会出错吗?如果安全,我将忽略此警告并删除我的简短警告说明
  • 如何完全遵循警告?
  • 最佳答案

    那不是可调用的。

    您在这里有两个选择:

  • 依赖 dict 作为默认值;如果没有提供,这将导致您的模型使用空的 dict {}:
  • class UnderwritingValidator(TimeStampedModel):
        plan = models.PositiveIntegerField(null=True, blank=True, unique=True)
        logic = JSONField(default=dict)
    
  • 创建您自己的“可调用”并将其用作默认值:
  • def get_default_something():
        return {'accept_list': [], 'reject_list': []}
    
    class UnderwritingValidator(TimeStampedModel):
        plan = models.PositiveIntegerField(null=True, blank=True, unique=True)
        logic = JSONField(default=get_default_something)
    

    10-07 17:22