I faced a very weird issue with django drf. The below view does not deserializes the event_time
in post() method.
class EventListCreateView(generics.ListCreateAPIView):
class EventSerializer(serializers.ModelSerializer):
school_id = serializers.IntegerField(read_only=True)
class_number = serializers.CharField(source='class.universal_number', read_only=True)
class_id = serializers.IntegerField(write_only=True)
class Meta:
model = Event
fields = ('pk', 'event', 'school_id', 'class_number', 'class_id', 'event_time',)
serializer_class = EventSerializer
filterset_class = EventFilterSet
ordering_fields = ['event_time']
def get_queryset(self):
return (
Event.objects.select_related('class')
.annotate(school_id=F('class__school'))
.order_by('-pk')
)
It works only after I explicitly mention event_time
in the serializer:
class EventListCreateView(generics.ListCreateAPIView):
class EventSerializer(serializers.ModelSerializer):
school_id = serializers.IntegerField(read_only=True)
class_number = serializers.CharField(source='class.universal_number', read_only=True)
class_id = serializers.IntegerField(write_only=True)
event_time = serializers.DateTimeField()
class Meta:
model = Event
fields = ('pk', 'event', 'school_id', 'class_number', 'class_id', 'event_time',)
serializer_class = EventSerializer
filterset_class = EventFilterSet
ordering_fields = ['event_time']
def get_queryset(self):
return (
Event.objects.select_related('event_class')
.annotate(school_id=F('class__school'))
.order_by('-pk')
)
The model :
class Event(models.Model):
event_class = models.ForeignKey(Class, on_delete=models.DO_NOTHING)
event = models.CharField(choices=EventNameEnum.choices, max_length=50, db_index=True)
event_time = models.DateTimeField(editable=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'Event id: {self.pk} , Device id: {self.event_class.pk}'
Which doesn't make sense to be correct approach. Any suggestion on how to solve the issue will be appreciated.
I found the cause of the issue.
It stemmed from editable=False
in the event_time declaration in the model:
event_time = models.DateTimeField(editable=False)
When the field is declared as none editable, it should be explicitly declared in the serializer to be included in deserialization.