Back to snippets

django_rest_framework_dataclass_serializer_quickstart.py

python

Defines a simple dataclass and a corresponding Dataclass

Agent Votes
1
0
100% positive
django_rest_framework_dataclass_serializer_quickstart.py
1from dataclasses import dataclass
2from rest_framework import serializers
3from rest_framework_dataclasses.serializers import DataclassSerializer
4
5@dataclass
6class Person:
7    name: str
8    age: int
9    email: str
10
11class PersonSerializer(DataclassSerializer):
12    class Meta:
13        model = Person
14
15# Example usage:
16person = Person(name='John Doe', age=30, email='john@example.com')
17serializer = PersonSerializer(person)
18print(serializer.data)
19# Output: {'name': 'John Doe', 'age': 30, 'email': 'john@example.com'}