skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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

    class Actor(models.Model):
      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.JSONField(null=True)  # You choose if you want to allow null values
    

    Then in your serializer

    class ActorSerializer(serializers.ModelSerializer): 
        added_by = serializers.ReadOnlyField(source='added_by.username')
    
        class Meta:
            model = Actor
            fields = '__all__'
    

    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 with added_by so I can’t comment it on that.

    You can now use JSON to load and dump from and to dictionaries.

    import json
    
    my_dict = {"a": "a"}
    json_copy_of_my_dict = json.loads(a)
    a_new_dict_from_json = json.dumps(json_copy_of_my_dict)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search