Reputation: 17284
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
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
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