简体   繁体   中英

Get values of Enum fields from Django Queryset

I have a model with an enum column, eg

# Using Django 2.2 (does not support Enums natively)
from django_enum_choices.fields import EnumChoiceField

class Service(Enum)
    MOBILE: "MOBILE"
    LAPTOP: "LAPTOP"


class Device(models.Model):
    service = EnumChoiceField(Service)
    ...

Is it possible to get get the query results with the enumerated column being the value of the enum?

For example: If I do:

query = Device.objects.values("service")
print(query)

I get: <QuerySet [{'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.MOBILE: 'MOBILE'>}, {'service': <Service.LAPTOP: 'LAPTOP'>}]>

I wish to get: <QuerySet [{'service': 'MOBILE'}, {'service': 'MOBILE'}, {'service': 'LAPTOP'}]>

I get errors when I run: query = Device.objects.values("service__value") or query = Device.objects.values("service.value")

I want to something like how we can get value of an enum field by saying

mobile_service = Service.MOBILE # <Service.MOBILE: "MOBILE">
mobile_service_as_string = mobile_service.value # "MOBILE"

The errors:

  1. django.core.exceptions.FieldError: Cannot resolve keyword 'value' into field. Join on 'service' not permitted.
  2. django.core.exceptions.FieldError: Cannot resolve keyword 'service.value' into field. Choices are: service, ..

It turns out that you can just use a serializer!

from django_enum_choices.serializers import EnumChoiceModelSerializerMixin
from rest_framework import serializer


class DeviceSerializer(EnumChoiceModelSerializerMixin, serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = (
            "service",
        )

Results:

query = Device.objects.values("service").all()
results = DeviceSerializer(query, many=True)
print(results)

# [OrderedDict([('service', 'MOBILE')]), OrderedDict([('service', 'LAPTOP')])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM