Django Rest Framework: Correct way to serialize ListFields

2024/10/8 14:43:02

Based on the DRF documentation I have a created a list of email_id stored in my model in the following way Models.py

class UserData(models.Model):emails = models.CharField(max_length=100,blank=False)

In my serializers.py file

class UserSerializer(serializers.ModelSerializer):emails = serializers.ListField(child = serializers.EmailField())

While posting the data, the drf page shows the data in the expected format, i.e

"emails": ["[email protected]"],

But, if I query the same data using python or any rest client. I get the data in the following format

data = json.load(urllib2.urlopen("http://localhost:8000/blah/id"))
In [46]: d['emails']
Out[46]: 
[u'[',u'u',u"'",u'b',u'a',u'l',u'@',u'b',u'a',u'l',u'.',u'c',u'o',u'm',u"'",u']']

Ideally, it should have been

d['emails'] = ['[email protected]'] 

I am not sure, what exactly is wrong in here. Any suggestions ?

Answer

Your model only has one email field. It does not support storing multiple email in the database. What you need is something like this:

class UserEmail(models.Model)user = models.ForeignKey('User', related_name='emails')email = models.EmailField(unique=True)# You can also store some other useful things here...activated = models.BooleanField(default=False)  # For exampleclass User(models.Model):...class EmailSerializer(serializers.ModelSerializer):class Meta:fields = ['id', 'email']class UserSerializer(serializers.ModelSerializer):emails = EmailSerializer(many=True)

However, this will result in a slightly different data structure:

[{'someUserField': 'foobar','emails': [{'id': 1, 'email': '[email protected]'},{'id': 2, 'email': '[email protected]'},]
}, {...
}]

If you don't want this data structure, you could create a custom field

Or... if you're using postgresql you should be able to do this:

from django.contrib.postgres.fields import ArrayFieldclass UserData(models.Model):emails = ArrayField(models.EmailField(), blank=True)
https://en.xdnf.cn/q/70115.html

Related Q&A

Flask-SQLAlchemy TimeoutError

My backend configuration is :Ubuntu 12.04 Python 2.7 Flask 0.9 Flask-SQLAlchemy Postgres 9.2Ive got this error message: TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed ou…

Making saxon-c available in Python

I have just read that Saxon is now available for Python, and thats just great fun and good, but can anyone write a tutorial on how to make it available for Python/Anaconda/WingIDE or similar? I am use…

How to include multiple interactive widgets in the same cell in Jupyter notebook

My goal is to have one cell in Jupyter notebook displaying multiple interactive widgets. Specifically, I would like to have four slider for cropping an image and then another separate slider for rotati…

SWIG - Problem with namespaces

Im having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I dont wrap it in a namespace, b…

Django access to subclasses items from abstract class

class Animal(models.Model):....class Meta:abstract = Trueclass Cat(models.Model, Animal):...class Dog(models.Model, Animal):....I want to be able to return all instances of querysets of all the subclas…

Django BinaryField retrieved as memory position?

Ive written a short unit test with the following code:my_object = MyObject() my_object.data = b12345my_object.save() saved_object = MyObject.objects.first()assert saved_object.data == my_object.datawhe…

difflib.SequenceMatcher isjunk argument not considered?

In the python difflib library, is the SequenceMatcher class behaving unexpectedly, or am I misreading what the supposed behavior is?Why does the isjunk argument seem to not make any difference in this…

PyCharm Code Folding/Outlining Generates Wrong Boundaries

Im having a very frustrating issue with PyCharm in that it does not want to properly outline the code so that blocks fold correctly. Ive looked all over the place and couldnt find any help with this pa…

How to clear the conda environment variables?

While I was setting an environment variable on a conda base env, I made an error in the path that was supposed to be assigned to the variable. I was trying to set the $PYSPARK_PYTHON env variable on th…

Create duplicates in the list

I havelist = [a, b, c, d]andnumbers = [2, 4, 3, 1]I want to get a list of the type of:new_list = [a, a, b, b, b, b, c, c, c, d]This is what I have so far:new_list=[] for i in numbers: for x in list: f…