Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 200
joe Avatar asked Oct 11 '19 03:10

joe


1 Answers

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)
like image 146
Alex Avatar answered Nov 13 '22 18:11

Alex