tags:

views:

90

answers:

2

For example this chunk of code:

new_log = ActivityLog(user=self.user,
                      activity=activity)
new_log.save()

Can I chain it to be like new_log = ActivityLog(...).save() ?

I believe I tried the above, but it doesn't work. Is there a way to make it a 1 liner?

+6  A: 

Let save() return self, such as:

class ActivityLog (object): # EDIT: OR INHERIT FROM WHATEVER OTHER CLASS, I DONT CARE
    ...

    def save(self):
        ...
        return self

NOTE: This is a generic coding pattern called method chaining.

catchmeifyoutry
I must be missing something... how does this work if ActivityLog doesn't inherit from models.Model?
Jarret Hardie
what ` model.Model` ? There is no framework specific tag, just some generic python code. Please don't assume python == Django.
catchmeifyoutry
You make a good point... I agree I did assume Django.
Jarret Hardie
Well, you seem to have been right to assume that. However, this is a more generic coding pattern called "method chaining".
catchmeifyoutry
+2  A: 

Django provides a convenience method on the model manager for just this purpose :-)

new_log = ActivityLog.objects.create(user=self.user, activity=activity)

The docs on create are here. It is billed as:

A convenience method for creating an object and saving it all in one step.

Jarret Hardie