Home > Software design >  How to add array of integer field in Django Rest Framework?
How to add array of integer field in Django Rest Framework?

Time:12-01

I want to add an array of integer fields in my model

class Schedule(models.Model):
    name = models.CharField(max_length=100)
    start_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(null=True, blank=True)
    day_of_the_week = ?? ( array of integer )

I tried with

class Schedule(models.Model):
    name = models.CharField(max_length=100)
    start_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(null=True, blank=True)
    day_of_the_week = models.CharField(max_length=100)

and in the serializer add ListField

class ScheduleSerializer(serializers.ModelSerializer):
    day_of_the_week = serializers.ListField()

    class Meta():
        model = Schedule
        fields = "__all__"

but this one is not working can anyone suggest me how to deal with this issue?

CodePudding user response:

Try this:

class Schedule(models.Model):
    name = models.CharField(max_length=100)
    start_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(null=True, blank=True)
    day_of_the_week = models.JSONField(default=list)

class ScheduleSerializer(serializers.ModelSerializer):
    day_of_the_week = serializers.ListField(
        child=serializers.IntegerField(),
    )

    class Meta():
        model = Schedule
        fields = "__all__"

CodePudding user response:

Your solution should work with one small modification:

models.CharField(validators=[int_list_validator], max_length=100)
  • Related