#34397: Subclasses of JSONField call `get_prep_value` with field as value
-------------------------------------+-------------------------------------
Reporter: pheki | Owner: nobody
Type: Bug | Status: new
Component: Database | Version: 3.2
layer (models, ORM) |
Severity: Normal | Keywords:
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
Hi!
Let's say I have a class called PhoneNumber:
{{{
@dataclass
class PhoneNumber:
country_iso_code: str
national_number: int
}}}
I create a field I use to use PhoneNumber in my database:
{{{
class PhoneNumberField(JSONField):
def get_prep_value(
self, value: Optional[PhoneNumber]
) -> Optional[JsonAdapter]:
if isinstance(value, PhoneNumber):
return JsonAdapter(dataclasses.asdict(value),
encoder=CustomJSONEncoder)
elif value is None and self.null:
return None
else:
raise Exception("Fetching phone number with unexpected value")
# Similar from_db_value ommited
def from_db_value(...):
...
}}}
The problem is that when I do a KeyTextTransform to get a field, it will
call get_prep_value with that field and AFAIK there's no way to know which
field is it getting. For from_db_value the same happens, but it's fine as
you can inspect the expression column. Example:
{{{
User.objects.annotate(
national_number=KeyTextTransform("national_number", "phone_number")
).filter(
national_number="12345678"
)[0]
}}}
Will call `field.get_prep_value("12345678")`, forcing the only way to make
it work correctly to silently ignore unexpected types. This didn't happen
on django 2.2 for `django.contrib.postgres.fields.jsonb.JSONField`.
--
Ticket URL: <https://code.djangoproject.com/ticket/34397>
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/01070186c708b6a4-e9411730-7850-42de-ad45-30622db6b1db-000000%40eu-central-1.amazonses.com.