Search code examples
pythonpeeweeflask-peewee

How to check (count) are returned data?


I have got this query in Peewee:

return c = Products.get(Products.sku == article).get()

How to check if it returns data?

I tried:

if c.count() > 0:

if len(c) > 0

It does not work for me

This is full code:

try:
    r = self.isProductExist(row['sku'])

    ## if (r.count() == 0):

except peewee.DoesNotExist:

   # Insert product


    def isProductExist(self, article):
      return Products.get(Products.sku == article).get()

Solution

  • Your code is all kinds of wrong.

    First of all, the 2nd call to "get()" is not necessary here:

    return c = Products.get(Products.sku == article).get()
    

    Second of all, you are returning an assignment (?) which makes no sense. Change to:

     return Products.get(Products.sku == article)
    

    If the product exists, it will be returned. If not, a DoesNotExist exception will be raised, making it unnecessary to call "count()" anywhere.

    To make the code work even if the product is not found:

    try:
        return Products.get(Products.sku == article)
    except Products.DoesNotExist:
        # Product was not found.
        return