如何在Django Rest Framework中添加整数字段数组?

py49o6xq  于 2022-12-01  发布在  Go
关注(0)|答案(2)|浏览(108)

我想在模型中添加一个整型字段数组

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 )

我试过

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)

并在序列化程序中添加ListField

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

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

但是这个不起作用,有没有人能建议我如何处理这个问题?

42fyovps

42fyovps1#

试试这个:

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__"
mum43rcc

mum43rcc2#

您的解决方案只需做一个小小的修改:

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

相关问题