I have a model that looks something like this
class Post(models.Model):
id = models.IntegerField(unique=True, primary_key=True)
title = models.CharField(max_length=150, blank=True)
created = models.DateTimeField(blank=True)
...
I have to fill the database with chunks of data. I am getting the data in form of a flat json string (no nesting) so my work is pretty easy i.e.
mydict = json.loads(jsonstr)
mypost = Post(**mydict)
mypost.save()
there is just one issue that the date-time is expressed in "YYYY-MM-DDThh:mm:ss+zzzz" format ( e.g. "created" : "2011-11-17T09:21:31+0000"
) which breaks the above code.
I know forms.DateTimeField
has input_formats
. Is there a way I could make DateTimeField accept above format?
Subclass DateTimeField and convert the value appropriately:
class ConvertingDateTimeField(models.DateTimeField):
def get_prep_value(self, value):
return str(datetime.strptime(value, FORMAT_STRING))
Then use ConvertingDateTimeField to replace models.DateTimeField.
There's probably a better way to do it if you look how DateTimeField creates the datetime object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With