nubela
nubela

Reputation: 17284

How do I chain object instantiation with its methods?

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?

Upvotes: 0

Views: 205

Answers (2)

catchmeifyoutry
catchmeifyoutry

Reputation: 7349

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.

Upvotes: 6

Jarret Hardie
Jarret Hardie

Reputation: 97902

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.

Upvotes: 2

Related Questions