Given some model
class Loan(models.Model):
time_of_loan = models.DateTimeField()
username = models.CharField()
I have attempted to use the ModelSerializer
from Django's REST Framework to serialize the Loan
.
class LoanSerializer(serializers.ModelSerializer):
time_of_loan = serializers.DateTimeField(
format=None, input_formats=['%Y-%m-%d %H:%M:%S',])
class Meta:
model = `Loan`
fields = ['time_of_loan', 'username']
On using the serializer.data
to get the JSON format, when I save the first time, the first time the model is saved, the JSON is well-behaved.
{
'time_of_loan': '2016-06-20 00:00:00+08:00',
username: 'doe'
}
However, when I attempt to update the model, it "misbehaves" and it appears in a python datetime
format.
{
'time_of_loan': datetime.datetime(2016, 6, 20, 7, 55, tzinfo=<UTC>),
'username': 'doe'
}
What change do I need to do so that, whenever the model gets serialized, it remains as the first format that I want?
FIRST EDIT
Can you show what you're doing to update the objectThe question asked was what I did to update the model. I actually am using this as an audit log and so it took from an actual Django Form. In forms.py
:
id = forms.cleaned_data.get('id')
username = forms.cleaned_data.get('username')
loan = Loan.objects.filter(id=id) #Queryset with count() = 1
loan.update(username=username)
loan_obj = loan[0]
serializer = LoanSerializer(loan_obj)
print(serializer.data)
Aucun commentaire:
Enregistrer un commentaire