Reputation: 6703
I want to make a post api,
users give me name
and location
and I save it
but I have a filed called datetime
is not null,And it need to count
Please teach me how to deal with this situation
My models has 3 fileds:
class Data(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
datetime = models.DateTimeField(auto_now=False, auto_now_add=False)
location = models.CharField(max_length=255, null=True, blank=True)
serilizers.py
class DataSerializer(serializers.ModelSerializer):
class Meta:
model = Data
fields = ( 'name','location' )
views.py
class DataList(generics.ListCreateAPIView):
queryset = Data.objects.all()
serializer_class = DataSerializer
def pre_save(self, obj):
obj.datetime = datetime.now()
I find pre_save()
function on the web ,
I thought it can help me save datetime
datetime field
But ths answer is no
How can I save the datetime
after I deal with it
Now I had error :
NOT NULL constraint failed: data.datetime
Upvotes: 1
Views: 1742
Reputation: 1821
I had a similar problem, I knew it was caused by the ORM trying to insert a null value in a non-nulable field, I was passing the right parameter to the API but the problem is with the serializer, add the datetime field to serilizers.py like this:
class DataSerializer(serializers.ModelSerializer):
class Meta:
model = Data
fields = ( 'name', 'datetime', 'location' )
Upvotes: 0
Reputation: 688
It seams to me that you're actually trying to implement the functionality of auto_now_add=True, which you're specifically prevent it at the model level.
Why isn't auto_add_now good for what you're trying to achieve: the timestamp of object creation?
Upvotes: 0
Reputation: 20976
Since you're using 3.x your best option is to pass the serializer.save()
an extra argument that will be pushed to the object's save:
class DataList(generics.ListCreateAPIView):
queryset = Data.objects.all()
serializer_class = DataSerializer
def perform_create(self, serializer):
serializer.save(datetime=datetime.now())
The serializer will add the datetime
argument to validated_data
used to create the instance.
Upvotes: 3