DateTimeField throwing datetime is not serializeable

I have added a new Datetime field in my model.

class MyModel:
    valid_upto = models.DateTimeField(auto_now=True, blank=True, null=True)

and my serializer code is

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

When i am updating one instance i am getting TypeError: Object of type datetime is not JSON serializable the value that can come in valid_upto is None or a datetime value which i am getting from timezone.now()

probably you are wrong with field attribute. More here: https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.DateField.auto_now

class MyModel:
    valid_upto = models.DateTimeField(auto_now=True, auto_now_add=True)

By default this field is not editable. And serializer should check it. But if you want, you remove this field manually:

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        exclude = ('valid_upto', )
Back to Top