Reputation: 21
I've created an API with rest_framework and can receive API calls that updates the database, but I can't figure how to query the database and return any row where the field "Endtime" is NULL.
In the function below I'm updating the database with the received JSON-data and this fails to return any result where the value is NULL for Endtime. Below is the error I get. How should I write the view to return rows where endtime column is NULL?
ValidationError at /durationupdate/
['“NULL” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
Request Method: POST
Request URL: http://127.0.0.1:8000/durationupdate/
Django Version: 4.1.1
Exception Type: ValidationError
Exception Value:
['“NULL” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
views.py `
@api_view(['POST', 'GET'])
def durationUpdate(request):
if request.method == 'POST':
serializer = RigstateSerializer(data=request.data)
wherenull = Rigstate.objects.get(endtime='NULL')
wherenullserializer = DurationSerializer(wherenull, many=True)
if serializer.is_valid():
serializer.save()
return Response(wherenullserializer.data)
`
models.py `
class Rigstate(models.Model):
rigname = models.CharField(max_length=255)
rigmode = models.IntegerField(default=0)
starttime = models.DateTimeField()
endtime = models.DateTimeField(blank=True, null=True)
duration = models.IntegerField(default=0)
def __str__(self):
return self.rigname
`
I've tried changing from 'NULL' to NULL but then I get a different error
Upvotes: 1
Views: 42
Reputation: 21
Changed name to a more appropriate (DurationList)
views.py
@api_view(['GET'])
def durationList(request):
if request.method == 'GET':
duration = Rigstate.objects.values_list('endtime')
wherenullserializer = DurationSerializer(duration, many=True)
return Response(wherenullserializer.data)
Most changes were in serializers.py
class DurationSerializer(serializers.ModelSerializer):
class Meta:
model = Rigstate
endtime = serializers.DateTimeField(allow_null=True)
fields = ('endtime',)
Now I only get columns where entime is null, and only the endtime value
Upvotes: 1
Reputation: 14391
You should your endtime
write only and override to_represenation
method like this.
class RigstateSerializer(serializer.ModelSerializer):
class Meta:
model = Rigstate
fields = '__all__'
extra_kwargs = {'endtime': {'write_only': True}}
def to_representation(self, instance):
data = super().to_representation(instance)
if instance.endtime:
data['endtime'] = instance.endtime.strftime(#write you required format here)
return data
Upvotes: 1