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 b开发者_如何学Ce 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?
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.
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.
精彩评论