我有如下模型
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
以下哪一项是更新ShipmentHistory表中的行的最佳方法。你知道吗
使用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
使用查询筛选器
history = ShipmentHistory.objects.filter(airwaybill_number=1000)
if history.exists()
history[0].last_added_bag = 'abc'
# update other fields
history[0].save()
else:
# create history record first then update
特定装运的历史记录将至少更新十几次。你知道吗
我从未见过这样定义的django模型,我希望,这只是一个伪模型
两个查询都是两个不同的查询。
.get()
对.filter()
。后者提供queryset,而.get()
提供一个对象。你知道吗对于} 而不是try/catch。在您的例子中,
.get()
,您没有太多的优化选项,但是可以使用^{get()
的问题是,如果有多个,您可能会得到MultipleObjectsReturned。这就是为什么我会选择带filter()的那个。你知道吗是的,比cd7便宜。你知道吗
您可能需要使用
Queryset.get_or_create()
(https://docs.djangoproject.com/en/1.7/ref/models/querysets/#get-or-create):相关问题 更多 >
编程相关推荐