[Django] #29388: JSONField defaults to empty list gets modified

7 views
Skip to first unread message

Django

unread,
May 8, 2018, 4:59:00 AM5/8/18
to django-...@googlegroups.com
#29388: JSONField defaults to empty list gets modified
--------------------------------------------+------------------------
Reporter: Ponytech | Owner: (none)
Type: Bug | Status: new
Component: contrib.postgres | Version: 2.0
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
--------------------------------------------+------------------------
Consider this simple model :


{{{
from django.db import models
from django.contrib.postgres.fields import JSONField


class Thing(models.Model):
name = models.CharField(max_length=100)
features = JSONField(default=[], blank=True)
}}}


And this code snippet :

{{{
>>> t1 = Thing.objects.create(name="thing 1")
>>> t1.features.append({"f1": 42, "f2": 56})
>>> t1.features
[{'f1': 42, 'f2': 56}]
>>> t1.save()
>>> t2 = Thing.objects.create(name="thing 2")
>>> t2.features
[{'f1': 42, 'f2': 56}]
}}}

I'd expect t2 features to be an empty list.

My guess is the model default fields gets modified somehow.

--
Ticket URL: <https://code.djangoproject.com/ticket/29388>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

Django

unread,
May 8, 2018, 6:05:55 AM5/8/18
to django-...@googlegroups.com
#29388: JSONField defaults to empty list gets modified
----------------------------------+--------------------------------------
Reporter: Ponytech | Owner: (none)
Type: Bug | Status: closed
Component: contrib.postgres | Version: 2.0
Severity: Normal | Resolution: invalid

Keywords: | Triage Stage: Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
----------------------------------+--------------------------------------
Changes (by Jani Tiainen):

* status: new => closed
* resolution: => invalid


Comment:

You've hit Python mutable default problem. Instead of defining mutable
default `[]` use callable as default `list` in this particular case.

See [[TicketClosingReasons/UseSupportChannels]] for further information

--
Ticket URL: <https://code.djangoproject.com/ticket/29388#comment:1>

Reply all
Reply to author
Forward
0 new messages