Django:哪种方式更好的方法来查找(搜索)一个相等的数据对象?

时间:2016-09-26 21:13:31

标签: python django

我正在Django中实施搜索功能,其中哪些会更好?

def same_cart_item_in_cart(cart, new_cart_item):
    already_exist_cart_item = cart.cartitem_set.filter(
        Q(variation__product=new_cart_item.variation.product),
        Q(variation=new_cart_item.variation),
        Q(width=new_cart_item.width),
        Q(height=new_cart_item.height),
    ).first()

    return already_exist_cart_item    # It can be None

首先覆盖CartItem' __eq__

class CartItem(TimeStampedModel):
    cart = models.ForeignKey("Cart")
    variation = models.ForeignKey(Variation)
    # 벽화 너비
    width = models.PositiveIntegerField(
        default=1,
        validators=[MinValueValidator(1)],
    )
    # 벽화 높이
    height = models.PositiveIntegerField(
        default=1,
        validators=[MinValueValidator(1)],
    )
    quantity = models.PositiveIntegerField(
        default=1,
        validators=[MinValueValidator(1)],
    )

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return str(self.variation.product) + ' - ' + str(self.variation)

    def __eq__(self, other):
        return (
            self.variation.product == other.variation.product and
            self.variation == other.variation and
            self.width == other.width and
            self.height == other.height
        )

然后,

def same_cart_item_in_cart(cart, new_cart_item):
    for cart_item in cart.cartitem_set.all():
        if cart_item == new_cart_item:
            return cart_item

    return None

1 个答案:

答案 0 :(得分:0)

正如我在评论< 1>中所述。选项更好。

你正试图保存新实例并在保存之前检查它,Django为你做了。您可以将unique_together添加到Model Meta,如果您尝试保存部分相同的对象,则会引发错误。

<强>更新

它应该使用using foregn key values directly

优化您的代码

所以你的代码将是

def same_cart_item_in_cart(cart, new_cart_item):
    already_exist_cart_item = cart.cartitem_set.filter(
        Q(variation_id=new_cart_item.variation_id),
        Q(width=new_cart_item.width),
        Q(height=new_cart_item.height),
    ).first()

    return already_exist_cart_item 

我删除了Q(variation__product=...),如果Variation实例相同,则无需查询其字段。并将Q(variation=...)更改为Q(variation_id=...)