2

I have a model that contains the newly added ListField class in DRF. I am trying to store a List of strings so the output would look like so:

{

    "hashtags":["something", "new"],

}

I'm pretty new to working with DRF but I seem to be having some trouble serializing the result. When I run the request I received a HashField() is not JSON serializable error. Again I'm new to working with the the framework and Python in general but any suggestions, point in the right direction would be a help.

models.py

class HashField(serializers.ListField):
    child = serializers.CharField(max_length=100)

 class Mention(models.Model):
    author = models.ForeignKey(User)
    hashtags = HashField()      
    placename = models.CharField(max_length=140, default='SOME STRING')
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.placename

serializers.py

class MentionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Mention
1

1 Answer 1

1

Django REST Framework has different kind of serializers, what you need here is a field serializer that validates a list type. in serializers.py do as follow:

class MentionSerializer(serializers.ModelSerializer):
    hashtags = serializers.ListField()
    class Meta:
        model = Mention
Sign up to request clarification or add additional context in comments.

6 Comments

thank @dhiatn. I tried that, now getting exception "Got a TypeError when calling Mention.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Mention.objects.create(). You may need to make the field read-only, or override the MentionSerializer.create() method to handle this correctly. Original exception text was: 'hashtags' is an invalid keyword argument for this function."
@gregdevs I will recommend to use ArrayField in th model field: hashtags = ArrayField(models.CharField(max_length=100), blank=True) and the serializers.ListField in the DRF serializer hashtags = serializers.ListField().
that's right and it will be great if you switch to PostgreSQL, because in the next django realease 1.9 there will be more support for complex data-structure and PostgreSQL will offer you more flexiblity and efficiency. You still can you use this third party module jsonfield it works fine with MySQL too @gregdevs.
thanks, going to check this out in a bit, will let you know on my progress. thanks again for the help
great and best of luck
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.