#32898: get_or_create() with filter() has surprising behaviour
------------------------------------------+------------------------
Reporter: Jamie Cockburn | Owner: nobody
Type: Uncategorized | Status: new
Component: Uncategorized | Version: 3.2
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 |
------------------------------------------+------------------------
This documentation:
https://docs.djangoproject.com/en/3.2/ref/models/querysets/#get-or-create
That doc says you can combine `filter()` with `get_or_create()`. Great!
But the resulting behaviour is somewhat surprising.
Given the following model:
{{{#!python
class A(models.Model):
a = models.CharField()
b = models.CharField()
}}}
I would expect that the following two lines would be fuctionally
equivalent:
{{{#!python
A.objects.get_or_create(a="something", b="another")
A.objects.filter(a="something").get_or_create(b="another")
}}}
If an instance `{"a": "something", "b": "another"}` already exists in the
database then they ''are'' equivalent.
If the instance does not exist, the `filter().get_or_create()` version
will create an instance `{"a": "", "b": "another"}`, throwing away the
kwargs passed to `filter()`.
By example:
{{{#!python
# create instance
o, c = A.objects.get_or_create(a='something', b="another")
print(o.a, o.b, c)
# find it with filter
o, c = A.objects.filter(a='something').get_or_create(b="another")
print(o.a, o.b, c)
# delete it again
A.objects.all().delete()
# create it with filter
o, c = A.objects.filter(a='something').get_or_create(b="another")
print(o.a, o.b, c)
}}}
Will output:
{{{
('something', 'another', True)
('something', 'another', False)
('', 'another', True)
}}}
This seems rather inconsistent, and should at least be flagged in the
docs.
--
Ticket URL: <https://code.djangoproject.com/ticket/32898>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/049.a66cd9a82e5c8054fe5d8460b2e9c371%40djangoproject.com.