Skip to content

Instantly share code, notes, and snippets.

@BigWhale
Last active February 1, 2021 15:25
Show Gist options
  • Save BigWhale/7864750b1bc727946df9970faad1dd95 to your computer and use it in GitHub Desktop.
Save BigWhale/7864750b1bc727946df9970faad1dd95 to your computer and use it in GitHub Desktop.
Django Rest Framework, conditionally required parameters
from rest_framework import serializers
#
# Use in your Serializer for fields that you want to be required only when certain crieteria is met
#
class ConditionalRequiredMixin(serializers.BaseSerializer):
# List of fields that may be required
conditionally_required: List[str] = []
# Override in your serializer to set required attribute
# on conditional fields
def condition_check(self) -> bool:
return False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field_name, field in self.fields.items():
if field_name in self.conditionally_required:
field.required = getattr(self, "condition_check")()
# Quick usage
class MyAwesomeSerializer(ConditionalRequiredMixin, serializers.ModelSerializer):
conditionally_required = ["foo", "bar"]
# Check if baz contains "Hit me one more time." and set fields foo and bar as required.
def condition_check(self) -> bool:
return self.context["request"].data["baz"] == "Hit me one more time."
class Meta:
model = Awesome
fields = [ "foo", "bar", "baz" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment