David Wolever
David Wolever

Reputation: 154574

django: use QuerySet.values() to return Python types?

I've got a custom Field which converts the value to/from a Python type:

class MyField(models.Field):
    # …
    def to_python(self, value):
        # …
        return MyType(value)

Is there any way to trick QuerySet.values(…) into running the field-specific conversions on the values it returns?

For example, I'd like something like this:

>>> MyModel.objects.all().values("my_field")
[{"my_field": MyType(…)}]

Instead of the current behaviour:

>>> MyModel.objects.all().values("my_field")
[{"my_field": "raw_database_value"}]

Obviously I can manually convert the result… But that's kind of lame =\

Upvotes: 2

Views: 948

Answers (1)

mmcnickle
mmcnickle

Reputation: 1607

No, this isn't possible. You can see the related ticket at https://code.djangoproject.com/ticket/9619

There you will see there is discussion whether values() should actually run any field-specific conversions.

As the ticket is marked "Design Decision Needed", you'd need to bring this up by posting to the django-developers mailing list, or raising it with someone on IRC (Freenode #django-dev)

In the meantime, you will have to manually convert the raw database value.

Upvotes: 2

Related Questions