Fildc
Fildc

Reputation: 33

Django objects.count() in default method parameter returns 0

I am still a novice in Django and quite baffled by the following:

I have a helper function for my tests, which creates an instance of model "Product", sets some properties and saves the instance to db:

def createTestProduct(product_group="VG", opno="MyProduct"+str(Product.objects.count())):
    p = Product()
    p.product_group = product_group
    p.own_product_no = opno
    p.save()
return p

When I call this function from a TestCase, the default parameter "opno" does not get the correct number of Products in the db:

class ProductListPageTest(TestCase):

    def test_product_list_displays_products(self):
        createTestProduct()
        print("# of Products: " + str(Product.objects.count()))
        print(Product.objects.all())
        createTestProduct()
        print("# of Products: " + str(Product.objects.count()))
        print(Product.objects.all())
        ...

The resulting output is (The Product model's __str__ method outputs the own_product_no property) :

# of Products: 1
[<Product: MyProduct0>]
# of Products: 2
[<Product: MyProduct0>, <Product: MyProduct0>]

My intention was to have the products numbered: MyProduct0, Myproduct1... Can anyone point me to my mistake? Thanks a lot in advance! Fildc

Upvotes: 1

Views: 174

Answers (1)

catavaran
catavaran

Reputation: 45575

Function argument evaluates once at the definition time so you shouldn't use any calculations in the def statement. Workaround for this situation is:

def createTestProduct(product_group="VG", opno=None):
    if opno is None:
        opno = "MyProduct%s" % Product.objects.count()
    ...

Upvotes: 2

Related Questions