Home > Back-end >  how to declare a serializer field containing list of ids in django
how to declare a serializer field containing list of ids in django

Time:08-18

Models:

class Author(Base):
    name = models.CharField(max_length=100, unique=True)

class Book(Base):
    name = models.CharField(max_length=100, unique=True)

class AuthorBookAssn(Base):
    author = models.ForeignKey(Author, on_delete=models.PROTECT)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)

I have an api to create a book, and along with the book data we would also get a list of author ids how should the serializer field be created such that it is a list of ids.

for example: [1, 2, 3]

This field would not be present in any models we only need to use these fields to create records in the AuthorBookAssn table.

CodePudding user response:

You could create a ModelSerializer that serializes a single object of the model

class AuthorBookAssnSerializer(serializers.ModelSerializer):
    class Meta:
        model = AuthorBookAssn
        fields = ['id']

and then when you try to validate a list of data such as [1, 2, 3] you can do the following

ids = [1,2,3]
AuthorBookAssns = AuthorBookAssnSerializer(ids, many=True)
AuthorBookAssns.data

CodePudding user response:

How to declare a serializer field containing list of ids in django make sure that you indent your code well the function must be on the class also when using SerializerMethodeField the function must start with get_ in this case function name to be triggered get_list_ids

class ProfileSerializers(serializers.ModelSerializer):
   list_ids = serializers.SerializerMethodField(read_only=True) 
   anyfield = serializers.CharField(source="")
   class Meta:
       model = Profile
       fields = (
           "list_ids",
           "anyfield ",
          
         )
   def get_list_ids (self, obj):
     my_ids = ModelName.objects.values_list('id', flat=True)
     return myids # this will return list of ids like <QuerySet [1, 2]>
# if you want to return list of tuples of ids use values_list: <QuerySet [(1,), 
 # (2,)]>
# if you want to return list of Dict user values <QuerySet [{'id': 1}, 
 # {'id': 2}]>
  • Related