Django复制数据库中的现有记录

时间:2011-11-29 13:04:37

标签: django

我正在尝试复制PostgreSQL数据库中的现有记录,每次点击重复按钮时,它似乎都会以2为增量进行复制。如果数据库中有1条记录,一旦按下该按钮,它将创建记录2和3。

模型

class Detail(models.Model):
    created = models.DateTimeField(auto_now_add=True, blank=False)
    last_update = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User, related_name='+')
    draft = models.BooleanField()
    outage_name = models.ForeignKey(Outage, related_name='+')
    group_name = models.CharField(max_length=100)
    shift = models.CharField(max_length=6)
    activity = models.CharField(max_length=100, null = False)
    culture_title = models.ForeignKey(Culture, related_name='+')
    work_completed = models.TextField()
    work_planned = models.TextField()
    radiation_info = models.TextField()
    action_item = models.TextField()
    lesson_learned = models.TextField()

查看

def turnover_copy(request, id):
    obj = Detail.objects.get(pk=id)
    obj.pk = None
    obj.draft = True
    if obj.draft:
        user = request.user.id
        obj.user_id = user
        obj.work_planned = 'My Work Planned.'
        obj.save()
        return HttpResponse('Created')
    else:
    return HttpResponse('Unable to duplicate template.')
编辑:我在模板中的for循环中使用了def,因此它不断创建重复项!

1 个答案:

答案 0 :(得分:1)

您确定代码因某些原因未被调用两次吗?一些打印语句可能会帮助您断言。