Django Rest Framework: the right way to serialize ListFields

Based on the DRF documentation, I created an email_id list stored in my model as follows 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()) 

When sending data, the drf page displays data in the expected format, i.e.

 "emails": [ " bal@bal.com " ], 

But, if I request 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'] = [' bal@bal.com '] 

I'm not sure what is wrong here. Any suggestions?

+5
source share
1 answer

There is only one email field in your model. It does not support storing multiple emails in a database. You need 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 example class User(models.Model): ... class EmailSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'email'] class UserSerializer(serializers.ModelSerializer): emails = EmailSerializer(many=True) 

However, this will lead to a slightly different data structure:

 [{ 'someUserField': 'foobar', 'emails': [ {'id': 1, 'email': ' foo@bar.maz '}, {'id': 2, 'email': ' bill@gates.ms '}, ] }, { ... }] 

If you do not want this data structure, you can create a custom field

Or ... if you are using postgresql , you should do this:

 from django.contrib.postgres.fields import ArrayField class UserData(models.Model): emails = ArrayField(models.EmailField(), blank=True) 
+1
source

Source: https://habr.com/ru/post/1239948/


All Articles