Django 1.11.1
以下是信号处理程序。这是关于保存历史。 不同的是信号(post_save和post-delete)和操作(+或 - )。
代码大多是重复的。你能帮我理解我怎么能坚持DRY原则吗?
@receiver(post_save, sender=FramePlace)
def save_add_place(sender, **kwargs):
current_request = CrequestMiddleware.get_request()
author = current_request.user
instance = kwargs.get('instance')
frame = instance.frame
place = instance.place
FramePlaceHistory.objects.create(author=author,
operation="+",
frame=frame,
place=place)
@receiver(post_delete, sender=FramePlace)
def save_delete_place(sender, **kwargs):
current_request = CrequestMiddleware.get_request()
author = current_request.user
instance = kwargs.get('instance')
frame = instance.frame
place = instance.place
FramePlaceHistory.objects.create(author=author,
operation="-",
frame=frame,
place=place)
答案 0 :(得分:0)
只需将代码放入函数中,它就可以保持代码简单(KISS)并且不会重复自己
@receiver(post_save, sender=FramePlace)
def save_add_place(sender, **kwargs):
create_frame("+", kwargs)
@receiver(post_delete, sender=FramePlace)
def save_delete_place(sender, **kwargs):
create_frame("-", kwargs)
def create_frame(operation, kwargs)
current_request = CrequestMiddleware.get_request()
author = current_request.user
instance = kwargs.get('instance')
frame = instance.frame
place = instance.place
FramePlaceHistory.objects.create(
author=author,
operation=operation,
frame=frame,
place=place
)