I have models like following
class Shipment(models.Model): airwaybill_number = models.IntegerField(primary_key=True) origin = models.CharField(max_length=50) destination = models.CharField(max_length=50) class ShipmentHistory(Models.Model): airwaybill_number = models.IntegerField(primary_key=True) last_added_bag = models.CharField(max_length=50, null=True, blank=True) ... some other fields which can be null
Which one of the following is the best way to update a row in ShipmentHistory table.
Using try / except
try: history = ShipmentHistory.objects.get(airwaybill_number=1000) history.last_added_bag = 'abc' # update other history fields history.save() except ShipmentHistory.DoesNotExist: # create the history record and then update
Using query filter
history = ShipmentHistory.objects.filter(airwaybill_number=1000) if history.exists() history.last_added_bag = 'abc' # update other fields history.save() else: # create history record first then update
The history records for a particular shipment will be updated atleast a dozen times.
- Do any of the methods have advantages over others, or is there a better way to do this?
- Is using a try / except a wrong method of implementation?
- Is the query filter option a more expensive query with regards to time?