I am trying to develop a POST API. I am trying to use a dictionnary to store social links of an actor model socials links should be stored in a variable socials in the Actor model.
socials= {"facebook":"www.facebook.com/" , "instagram":"www.instagram.com/" ,"linkedin":"www.linkedin.com/" }
Here is the actor model
model.py
class Actor:
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique=True)
bio = models.TextField()
created = models.DateTimeField(default=timezone.now )
updated = models.DateTimeField(auto_now=True)
socials = models.CharField(max_length=1024 , blank=True)
class Meta:
app_label = 'actors'
verbose_name = _('Actor')
verbose_name_plural = _('Actors')
ordering = ('name',)
def __str__(self):
return self.name
serializer.py
class ActorSerializer(serializers.ModelSerializer):
added_by = serializers.ReadOnlyField(source='added_by.username')
socials = serializers.DictField(
child=serializers.URLField(max_length=200, min_length=None, allow_blank=False)
)
class Meta:
model = Actor
fields = '__all__'
views.py
class ActorListView(generics.ListCreateAPIView):
queryset = Actor.objects.all()
serializer_class = ActorSerializer
This is my code. But there is something missing in order to do what I want (I got an error).
Could any one suggest a solution ?
2
Answers
import Jsonfield and try using the jsonfield instead of CharField but i think CharField should also work.Better you tell the error you are facing
Difficult to say without seeing your errors, but if you are trying to return dictionaries via your API, then I would use the
models.JSONField
Then in your serializer
You won’t need to override the
socials
field in the serializer as it will automatically be serialized. I’m not sure what you’re doing withadded_by
so I can’t comment it on that.You can now use JSON to load and dump from and to dictionaries.