Django: Which way is better way to find(search) a equal data object?
<p>I am implementing searching functions in <code>Django</code>, which of these would be better?</p>

<pre><code>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
</code></pre>

<p>Override <code>CartItem</code>'s <code>__eq__</code> first.</p>

<pre><code>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
        )
</code></pre>

<p>and then,</p>

<pre><code>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
</code></pre>

<p>As i said in the comment &lt;1> option is better.</p>

<p>And it you are trying to save new instance and check it before saving, Django made it for you. You can add <a href="https://docs.djangoproject.com/en/1.10/ref/models/options/#unique-together" rel="nofollow"><code>unique_together</code></a> to your <code>Model</code> <code>Meta</code> and you it will raise error if you would try to save partly same object.</p>

<p><strong>UPDATE</strong></p>

<p>It should optimize your code with <a href="https://docs.djangoproject.com/en/1.10/topics/db/optimization/#use-foreign-key-values-directly" rel="nofollow">using foregn key values directly</a></p>

<p>So your code would be </p>

<pre><code>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 
</code></pre>

<p>I removed <code>Q(variation__product=...)</code>, if <code>Variation</code> instance is the same, you don't need to query on its fields. And changed <code>Q(variation=...)</code> to <code>Q(variation_id=...)</code></p>

python django