AJW
AJW

Reputation: 5873

django postgresql timestamp on entry creation is not ordered in the database

I am quite new to django and I have a small app, with the following models:

class TimeStampedModel(models.Model):

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    class Meta:
        abstract = True


class SomeModel(TimeStampedModel):
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    some_json = JSONField(blank=True,default=dict)

    def __str__(self):
        return self.uuid

I now make some requests to a webserver and write the return value of the request to the database via model forms like so:

    data = requests.get(BASE_URL)
    form_data=collections.OrderedDict()

    form_data[  "some_json"   ] = data.json()
    form = SomeModel (form_data)
    if form.is_valid():
        form.save()
        logger.debug( "***** GOOD: form saved from %s", data.json() )
    else:
        logger.debug("**   form not valid because: %s ", form.errors)
    pass

It seems to work fine, but when I inspect the database I see that the timestemps are not ordered :( So, the top 5 entries on the database look like so (for the created_at field):

2020-08-17 19:59:14.377394+01
2020-08-17 19:58:31.017813+01
2020-08-17 20:00:33.302018+01
2020-08-17 19:59:57.626536+01
2020-08-17 19:59:07.671274+01

I am baffled as to how the database can write in non-ascending time stamps.. Am I missing something here? Shouldnt the database contain ordered values for the created_at field? My naive thinking leads me to think: [1] I make the rerquest and get data [2] write data to database this process should create database entries in ascending order - no?

Since I use a logger, I can see that the values are fetched in acending order but it is not the case on the database.

Upvotes: 0

Views: 140

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

Shouldn't the database contain ordered values for the created_at field.

No. If you do not specify how to order the records, it can return records in any possible order. You can retrieve objects in an ordered order by using .order_by(…):

SomeModel.objects.order_by('created_at')

You can also specify a default ordering that is used if you do not specify one yourself by specifing an ordering [Django-doc]:

class TimeStampedModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        abstract = True
        ordering = ['created_at']

Upvotes: 1

Related Questions