在自定义保存方法中保存另一个对象

时间:2015-10-12 14:26:08

标签: django django-models

每次用户记录锻炼时,我都希望为锻炼中完成的每个锻炼保存一个事务日志条目。

class LogBook(models.Model):
    name = models.CharField(max_length=40)
    description = models.TextField(blank=True)
    exercises = models.ManyToManyField(Exercise, through='Measurement')
    workout_date = models.DateField(default=datetime.now)
    notes = models.TextField(blank=True)

    def save(self, *args, **kwargs):
        # Need to save first to get access to a newly created log's ID            
        super(LogBook, self).save(*args, **kwargs)
        workout_list = []
        workout_list.append(self.id)

        exercise_list = [exercise.id for exercise in self.exericises.all()]

class TransactionLog(models.Model):
    EVENT_CHOICES = (
        ('recalc', 'Priority Calculation'),
        ('action', 'Exercise'),
    )
    log_date = models.DateField(default=datetime.now)
    event_type = models.CharField(max_length=6, choices=EVENT_CHOICES)
    event_model = models.CharField(max_length=12)
    event_id = models.IntegerField()

因此,从LogBook的save方法中,我想保存新的TransactionLogs:

First log:
event_type = 'action'
event_model = 'workout'
event_id = workout_list[0]

Additional logs:
event_type = 'action'
event_model = 'exercise'
event_id = one log for each id in exercise_list

如何从LogBook的保存方法中保存新的TransactionLog模型?

作为一个额外的问题,我已经编写了一个视图来在重新计算时保存事务日志(event_type ='recalc'):

def transaction(user, event, model, id):
    tl = TransactionLog(event_type=event, event_model = model, event_id = id)
    tl.save()
    return

如果我定义了一种从LogBook的保存方法中保存的方法,我是否通过不以某种方式从LogBook的保存方法中调用事务函数来“违反”DRY?

1 个答案:

答案 0 :(得分:0)

我不确定理解你的问题,因为答案看起来非常简单。

假设您删除了user transaction参数,因为您没有使用它,只需添加到LogBook.save

transaction('action', 'workout', workout_list[0])
for id in exercise_list:
   transaction('action', 'exercise', id)

修改
在我看来,transaction函数应该是TransactionLog模型的类方法:

@classmethod
def transaction(klass, user, event, model, id):
    tl = klass(event_type=event, event_model = model, event_id = id)
    tl.save()
    return

然后,从view.py,您致电:TransactionLog.transaction(...)