如何在Django REST API中实现请求数据的自定义枚举验证?
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

