You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django REST API中实现请求数据的自定义枚举验证?

How to Add Custom Validation for UnitOfMeasureName in Django REST Framework

Got it, enforcing that UnitOfMeasureName only accepts your predefined set of values is straightforward in Django REST Framework. Here are two solid approaches to implement this:

Approach 1: Use a ChoiceField (Simplest Option)

If your only requirement is to restrict the field to your allowed list, using a ChoiceField is the most direct way—it handles validation automatically.

from rest_framework import serializers

# Define your allowed units as a constant (tuple pairs for label/value consistency)
ALLOWED_UNITS = [
    ("Each", "Each"),
    ("Grams", "Grams"),
    ("Ounces", "Ounces"),
    ("Pounds", "Pounds"),
    ("Kilograms", "Kilograms"),
    ("Metric Tons", "Metric Tons"),
]

class YourDataSerializer(serializers.ModelSerializer):
    # Replace your existing CharField with ChoiceField
    UnitOfMeasureName = serializers.ChoiceField(choices=ALLOWED_UNITS)

    class Meta:
        model = YourModel  # Swap with your actual model class
        fields = ['UnitOfMeasureName', ...]  # Include other relevant fields here

When a user submits an invalid value like invalid_one, DRF will automatically return a 400 Bad Request with an error message listing all valid choices.

Approach 2: Custom Validation Method (More Flexible)

If you need to add extra logic alongside the value check (or prefer to keep the field as a CharField), use a field-specific validation method.

from rest_framework import serializers

ALLOWED_UNITS = ["Each", "Grams", "Ounces", "Pounds", "Kilograms", "Metric Tons"]

class YourDataSerializer(serializers.ModelSerializer):
    UnitOfMeasureName = serializers.CharField()

    class Meta:
        model = YourModel
        fields = ['UnitOfMeasureName', ...]

    def validate_UnitOfMeasureName(self, value):
        # Check if the submitted value is in the allowed list
        if value not in ALLOWED_UNITS:
            raise serializers.ValidationError(
                f"Invalid UnitOfMeasureName. Allowed values are: {', '.join(ALLOWED_UNITS)}"
            )
        # Add any additional validation logic here (e.g., case normalization)
        return value

This method gives you full control—you can extend it later to handle things like case insensitivity or value transformations before returning the validated data.

Both approaches will trigger the exact validation error you need when an invalid value is sent in the request.

内容的提问来源于stack exchange,提问作者Pabasara Ranathunga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:00:21