Skip to content

Using Pre and Post Hooks

Hooks let you modify data sent from the frontend before it gets saved. This can be useful if you need to add a current user field. It should not be used as a replacement for Django model signals.

python
def lowercase_email(data, request=None):
    # Pre-hook (before validation)
    if 'email' in data:
        data['email'] = data['email'].lower()
    return data

def set_current_user(validated_data, request=None):
    # Post-hook (after validation, before saving)
    if request and request.user.is_authenticated:
        validated_data['creator'] = request.user
    return validated_data

# Register hooks
registry.register(User, 
    pre_hooks=[lowercase_email], 
    post_hooks=[set_current_user]
)

Best Practices

  1. Keep serializers simple - only customize what you need
  2. Test thoroughly - verify both serialization and deserialization
  3. Handle edge cases - validate input data properly
  4. Consider performance - especially with nested data structures
  5. Check schema output - ensure your API documentation is correct

Not MIT Licensed - See Licensing section for details