Django查询-最佳查询方法

2024-04-26 10:09:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下模型

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

特定装运的历史记录将至少更新十几次。你知道吗

  1. 有没有哪种方法比其他方法有优势,或者有没有更好的方法?你知道吗
  2. 使用try/except是一种错误的实现方法吗?你知道吗
  3. 查询过滤器选项是否是一个时间上更昂贵的查询?你知道吗

Tags: 方法truenumberaddedmodelsupdatelengthhistory
2条回答

我从未见过这样定义的django模型,我希望,这只是一个伪模型

Shipment:
   airwaybill_number (pk)
   origin (not null)
   destination (not null)

两个查询都是两个不同的查询。.get().filter()。后者提供queryset,而.get()提供一个对象。你知道吗

对于.get(),您没有太多的优化选项,但是可以使用^{}而不是try/catch。在您的例子中,get()的问题是,如果有多个,您可能会得到MultipleObjectsReturned。这就是为什么我会选择带filter()的那个。你知道吗

是的,比cd7便宜。你知道吗

您可能需要使用Queryset.get_or_create()https://docs.djangoproject.com/en/1.7/ref/models/querysets/#get-or-create):

history, created = ShipmentHistory.objects.get_or_create(airwaybill_number=1000)
# update the fields and save..

相关问题 更多 >