I have model and serializer, there is ArrayField(postgres) in that model.
Now I wanted to create a serializer field that will receive list [1,2]
and save it to object, but for a list and detail in serializer to show a list of JSON objects.
Model:
class User(models.Model):
email = models.EmailField('Email', unique=True, blank=False)
full_name = models.CharField(
'Full name', max_length=150, blank=True, null=True)
roles = ArrayField(
models.PositiveSmallIntegerField(),
default=list,
blank=True
)
Serializer:
class ArraySerializerField(ListField):
def __init__(self, queryset, serializer_class):
super(ArraySerializerField, self).__init__()
self.queryset = queryset
self.serializer_class = serializer_class
def to_representation(self, value):
if value:
qs = self.queryset.filter(pk__in=value)
return self.serializer_class(qs, many=True).data
return []
def to_internal_value(self, value):
super(ArraySerializerField, self).to_internal_value(value)
print(value) # [1, 2]
return value
class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
roles = ArraySerializerField(queryset=Role.objects.all(), serializer_class=RoleSerializer)
class Meta:
model = User
fields = ('id', 'email', 'full_name', 'roles')
def create(self, validated_data):
print(validated_data)
# {'email': 'test@test.com', 'full_name': 'Test', 'roles': []}
user = super(UserSerializer, self).create(validated_data)
return user
Now when I do list or detail request, everything is ok, I get a list of roles as JSON.
But when I try to POST data and send with this data:
{
"email": "test@test.com",
"full_name": "Test",
"roles": [1, 2]
}
validated_data
in create
method shows roles always as []
and object is saved without roles, but print from to_internal_value
shows [1, 2]
.
What am I doing wrong? It should save sent data because to_internal_value
works fine.
EDIT:
GET and LIST response gives me right format:
{
"id": 1,
"email": "test@test.com",
"full_name": "Test",
"roles": [
{
"id": 1,
"name": "Role 1"
},
{
"id": 2,
"name": "Role 2"
}
]
}
Have you tried this?
class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'full_name', 'roles')
def create(self, validated_data):
# check validated_data here
...
I'm not sure about the nature of SerializerExtensionsMixin
class here. Also I'm not sure the intention behind the queryset
and serializer_class
arguments of your custom ListField
In [7]: from rest_framework import serializers
In [8]: class UserSerializer(serializers.Serializer):
...: roles = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, required=False)
...: email = serializers.EmailField()
...: full_name = serializers.CharField()
...:
In [9]: data = {
...: "email": "test@test.com",
...: "full_name": "Test",
...: "roles": [1, 2]
...: }
In [10]: u = UserSerializer(data=data)
In [11]: u.is_valid()
Out[11]: True
In [12]: u.data
Out[12]: {'roles': [1, 2], 'email': 'test@test.com', 'full_name': 'Test'}
In [13]: data["roles"] = []
In [14]: u = UserSerializer(data=data)
In [15]: u.is_valid()
Out[15]: True
In [16]: u.data
Out[16]: {'roles': [], 'email': 'test@test.com', 'full_name': 'Test'}
In [17]: data["roles"] = ["foo","bar"]
In [18]: u = UserSerializer(data=data)
In [19]: u.is_valid()
Out[19]: False
In [20]: u.errors
Out[20]: {'roles': {0: [ErrorDetail(string='A valid integer is required.', code='invalid')], 1: [ErrorDetail(string='A valid integer is required.', code='invalid')]}}
Create a RoleSerializer
and use it in the UserSerializer
class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
roles = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, required=False)
class Meta:
model = User
fields = ('id', 'email', 'full_name', 'roles')
def create(self, validated_data):
# check validated_data here
...
Using a custom array field
class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'full_name', 'roles')
def create(self, validated_data):
# check validated_data here
...
Try switching to PrimaryKeyRelatedField
. Though you'll need to change your user model to use an actual relation. Which is generally a good idea because it'll help enforce data integrity with your project.
class User(models.Model):
email = models.EmailField('Email', unique=True, blank=False)
full_name = models.CharField(
'Full name', max_length=150, blank=True, null=True)
roles = models.ManyToManyField(Role, blank=True)
class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
roles = serializers.PrimaryKeyRelatedField(
many=True,
queryset=Role.objects.all(),
)
class Meta:
model = User
fields = ('id', 'email', 'full_name', 'roles')
def create(self, validated_data):
print(validated_data)
# {'email': 'test@test.com', 'full_name': 'Test', 'roles': []}
user = super(UserSerializer, self).create(validated_data)
return user
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.