[Fixed]-Creating related objects in a TestCase is not seen in Model method

1👍

What happens is when you use item_set in compute_total function it queries the database for all items with customer_id of ken.
But there are no items, and there is no ken because you didn’t actually persisted anything into the database. You just created some objects.

So what you need to do is:

ken = Customer(name="Ken")
ken.save() # Ken must be persisted before creating his items.
apple = Item(customer=ken, name="apple", price=10)
banana = Item(customer=ken, name="banana", price=2)
apple.save()
banana.save()

First we need to persist ken, so that the database creates an ID for him. Then we create apple and banana with that id as a foreign key, and persist them as well.

Leave a comment