Search code examples
djangomongodbdjango-modelsdjango-rest-frameworkdjongo

How to have list of strings in Django REST framework model using MongoDB


I am using Django version 2.2.11 with MongoDB as database

I a Simple Array Field to store a list of strings in a Django REST framework Model. I want the serialized JSON output to be like this.

{
   name : "John"
   roles : [ "string1", "string2" ]
}

I searched the internet and could only find implementation of this for PostgreSQL.

I just need to store the data of roles as string/list in database and need to display in proper format in api view.

Edit

I am attaching the model and serializers used.

class UserProfile(AbstractBaseUser, PermissionsMixin):
   username = None
   email = models.EmailField(max_length=255, unique=True)
   name = models.CharField(max_length=255, default="")

   is_active = models.BooleanField(default=True)
   is_staff = models.BooleanField(default=False)
   objects = UserProfileManager()

   USERNAME_FIELD = 'email'
   REQUIRED_FIELDS = ['name',]

   def get_full_name(self):
       return self.name

   def get_short_name(self):
       return self.name

   def __str__(self):
       return (self.name + " - " + self.email)



class UserDetails(models.Model):
   user_profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name = 'user_details', null = False)
   nickname = models.CharField(max_length=255, blank = True)
   about = models.TextField(max_length=50000, blank=True)
# role = 

 def __str__(self):
    return (self.user_profile.name +" - "+self.user_profile.email)

The serializer:

class UserDetailsSerializer(serializers.ModelSerializer):
    user_profile = UserProfileSerializer(read_only=True)

    class Meta:
        model = UserDetails
        fields = '__all__'

    def create(self, validated_data):
        user_profile = self.context['request'].user
        validated_data['user_profile'] = user_profile
        return super().create(validated_data)

The role field in the UserDetails Model should contain something like

role : ["President", "Admin"]

A JSON Array of strings.


Solution

  • This is the Workaround I used

    The djongo library natively doesn't support list of model fields. If you are using MongoDB, There are two options.

    1. Save the input as text file and serialize it into list when returned to API end.
    2. Use a Abstract Model class with one model field. Use the ArrayField from djongo library. This stores the data as objects in the database. You must handle the serializer methods manually. For get request, the serializer can use serializer.SerializerMethodField() and return the list of the primitive type (like Char) instead of list of Objects.

    I feel that the second option is better option.