开发者

How do I chain object instantiation with its methods?

开发者 https://www.devze.com 2022-12-14 12:27 出处:网络
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() ?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消