开发者

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

开发者 https://www.devze.com 2023-04-08 02:52 出处:网络
I\'ve got a custom Field which convert开发者_C百科s the value to/from a Python type: class MyField(models.Field):

I've got a custom Field which convert开发者_C百科s 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 =\


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消