VATSAL JAIN
VATSAL JAIN

Reputation: 581

Setting time field in django such that the stored time cannot be changed later

I have a orders model which looks like this:

class Order(models.Model):
    customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True)
    date_ordered=models.DateTimeField(auto_now=True)
    complete=models.BooleanField(default=False,null=True,blank=False)

and this is a specific view from my views.py:

def handlerequest(request, id):
    order=Order.objects.get(id=id)
    items=order.orderitem_set.all()
    verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum)
    PaytmHistory.objects.create(**response_dict)
    if verify:
        if response_dict['RESPCODE'] == '01':
            order.transaction_id=transaction_id
            order.complete=True               
            order.save()
            print('order successful')

Now what is happening is that whenever this is view is called the order is saved and the time updates to when the order was saved. But in future when I manually make some changes to the fields like when I update the shipping status of the order and save it then the time updates which I dont want . So is there any fix to this such that after

order.complete=True               
order.save()

The time cannot be changed

Upvotes: 0

Views: 39

Answers (2)

Achuth Varghese
Achuth Varghese

Reputation: 2451

  • Override the model save()
  • Check if Order.complete is True
  • Save with Order.date_ordered equal to current datetime when and only if Order.complete is True
  • date_odered field set to null=True, blank=True
class Order(models.Model):
    customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True)
    date_ordered=models.DateTimeField(null=True,blank=True)
    complete=models.BooleanField(default=False,null=True,blank=False)

    def save(self, *args, **kwargs):
        if self.complete == True:
            self.date_ordered = datetime.now

        super(Order, self).save(*args, **kwargs)

Upvotes: 1

iklinac
iklinac

Reputation: 15738

As documentation states auto_now

Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

You should use auto_now_add instead

automatically set the field to now when the object is first created. Useful for creation of timestamps.


Your field is still auto_now so you should remove auto_now from it and make it NULL=True, also you should set time value when you complete order and that is it.

Upvotes: 1

Related Questions