简体   繁体   中英

How to follow HINT: Use a callable instead, e.g., use `dict` instead of `{}`?

How to follow the warnings?

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=[]
    ))

Then 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

Software:

postgres: 10.9
Django==2.2.5

Questions:

  1. Am I safe from error? If it safe I will ignore this warning and erase my short warning note
  2. How to fully follow the warning?

That's not a callable.

You have two options here:

  1. Rely on dict as a default; this will result in your models using an empty dict {} if none is supplied:
class UnderwritingValidator(TimeStampedModel):
    plan = models.PositiveIntegerField(null=True, blank=True, unique=True)
    logic = JSONField(default=dict)
  1. Create your own "callable" and use it as default:
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM