Question

I have a django database (sqlite) which contains my models. In particular, there's one model with a date field which is not null in the database (confirmed with the sqlite shell), which dumpdata always serializes as null.

I'm using django 1.4.5 under python 2.7.5.

The part which is really odd is that it doesn't do this for all date fields. This seems to be the only field which is typed as datetime in the database, rather than just date.

My question is: what is causing this, and how can I stop it? Or alternatively, what's a good alternative to dumpdata?

Here's the model code:

class AccountTransaction(models.Model):
    value = models.FloatField()
    description = models.CharField(max_length = 1000)
    credit_in = models.ForeignKey(Organisation, on_delete = models.PROTECT, related_name='credits_in')
    debit_in = models.ForeignKey(Organisation, on_delete = models.PROTECT, related_name='debits_in')

    date = models.DateTimeField(auto_now_add=True) 

    class Meta:
        get_latest_by = 'date'

Here's the schema:

CREATE TABLE "mainapp_accounttransaction" 
("credit_in_id" integer, 
 "description" varchar(1000),
 "date" datetime NOT NULL DEFAULT '2012-06-18',
 "debit_in_id" integer,
 "id" integer PRIMARY KEY,
 "value" real);

And here's an example of an instance incorrectly serialised with a null date:

{
    "pk": 1,
    "model": "mainapp.accounttransaction",
    "fields": {
        "debit_in": 1,
        "date": null,
        "credit_in": 1,
        "description": "Charge for standard of Example5-1 limited (order Incorporation Order no. 13 for Example5-1 limited (UK Company temporary number: UN177efa40-2022-11e1-b383-e89a8f7f9c14))",
        "value": 100.0
    }
}

For comparison, here's the result of looking that up in the database:

sqlite> select * from mainapp_accounttransaction where id is 1;
1|Charge for standard of Example5-1 limited (order Incorporation Order no. 13 for Example5-1 limited (UK Company temporary number: UN177efa40-2022-11e1-b383-e89a8f7f9c14))|2012-06-18|1|1|100.0

Update: Here's a funny thing:

>>> import mainapp.models
>>> ats = mainapp.models.AccountTransaction.objects.all()
>>> [o.date for o in ats]
[None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]
Was it helpful?

Solution

It turns out that sqlite handles defaults oddly. Using the sqlite3 shell, select retrieves rows with the default value, but the Django ORM retrieves None values, because it appears that individual values have not been set for any of those objects.

The solution was to set values through the ORM for each object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top