bryansis2010 bryansis2010 - 1 year ago 352
Python Question

Django REST Framework DateTimeField format showing Python Time

Given some model

class Loan(models.Model):
time_of_loan = models.DateTimeField()
username = models.CharField()

I have attempted to use the
from Django's REST Framework to serialize the

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
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

'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?


Can you show what you're doing to update the object

The 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

id = forms.cleaned_data.get('id')
username = forms.cleaned_data.get('username')
loan = Loan.objects.filter(id=id) #Queryset with count() = 1

loan_obj = loan[0]
serializer = LoanSerializer(loan_obj)

Answer Source

After so much finding, I finally got the answer.

from rest_framework.renderers import JSONRenderer

serializer = LoanSerializer(loan_obj)
json = JSONRenderer().render(
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download