Week 3: Stale Copy: Object Identity in Related Models and Reloading Out-of-Sync Instances

The Task model in our application has a tree structure where tasks may have sub-tasks as children. We do this with a recursive relationship like this:

class Task(Model):
    parent = ForeignKey('self', related_name='children', null=True)
    finished = BooleanField(default=False)

I was testing a function that modifies a task and all its descendants, so my test looked a little like this:

def test_finish_all():
    task_1 = Task.objects.create()
    task_2 = Task.objects.create(parent=task_1)


    assert task_1.finished
    assert task_2.finished

The second assert fails. Is the problem with the test or the implementation? …

Week 3: Searching for Definition of a Model Attribute

One of the things I really appreciate about Python is how easy it is to navigate from a line of code that mentions some class or function to the source where that name is defined. For example, given

headers = SortedDict()

You may ask What's a SortedDict? Searching that source file for SortedDict, you find it's defined by

from django.utils.datastructures import SortedDict

But the definition of this model attribute is nowhere to be found. …

Week 2¾: The Extra Form

Over the weekend I was hanging out with some other coders and one of them asked me if I could help with ModelForms. I said I hadn't written any ModelForms yet, but I was sure to have to learn about them soon, so I offered to take a look with them.

There are five lights! (Continued…) …

Week 1: Tests, Transactions, and Tear Down

With our migrations fixed, we could now get on with the business of writing tests. Django uses Python's standard unittest package, which I'm well familiar with.1

We did a straightforward sort of TestCase, creating a User object and other instances of models needed by the code under test,2 we put that in a setUp method, and after we'd written a few of these, I asked shouldn't we write a tearDown method to clean up all these objects we've been creating?

My partner looked at me like I'd just suggested we put ice cubes on the pizza. Why would we do that?

Why, or why not, involves transactions. (Continued…) …

Week 1: Disappearing Text

We had a case where we wanted to replace some static text in a template with some text that changed depending on who was logged in. Textbook webdev 101 stuff. We added a property on the relevant model to return the correct phrase, we made sure that the model was accessible from something in the context, replaced the text in the template with a reference to this in some {{ curly brackets }} … and we came up with nothing. Or it showed up in some cases but not in other cases where we applied the |title filter.

Why? blocktrans. (Continued…)…