update_or_create不更新/创建对象

时间:2014-09-26 06:12:29

标签: django django-models django-queryset

我发现django 1.7现在支持queryset中的update_or_create()方法。 但是,当我尝试它时,它无法正常工作。我尝试这个时没有创建对象:

models.py

 class Model1(models.Model):
    name = models.CharField(max_length=100)
    status = models.CharField(max_length=100)
    user = models.ForeignKey(User, null=True, blank=True)

 class Model2(models.Model)
    model = models.ForeignKey(Model1, null=True, blank=True) 
    field1 = models.CharField(max_length=100)
    field2 = models.CharField(max_length=100)
    user = models.ForeignKey(User, null=True, blank=True)

views.py

 def ModelUpdate(request)
     model1 = get_object_or_404(Model1, pk=request.POST['lid'])
     model1.status =2
     model1.save()

     #based on the model1, we want to create or update model2 
     datadict ={'field1' : 1, 'field2':2,}
     model2, created = Model2.objects.update_or_create(model=model1,
                                                       defaults=datadict) 
     if created:
         print('model2 obj created') #for checking purpose
    else: 
         print('model2 obj not created')

    return render(request,'updated.html', {'update':'updated'})

我可以看到消息 model2 obj created 但该对象未保存在数据库中。可能是什么问题呢?

更新

原来这是我的错。在Model2中,我定义了save方法而不返回super(Model2, self).save(*args, **kwargs)
这就是为什么它没有保存对象。

1 个答案:

答案 0 :(得分:6)

也许你以错误的方式进行验证,因为我用你的模型创建了项目,一切正常。 就我而言,我正在验证是否使用objects.get()创建/更新了对象并打印了值:

In [1]: from app1 import models

In [2]: m1 = models.Model1.objects.create(name=1, status=1)

In [3]: m1
Out[3]: <Model1: Model1 object>

In [4]: datadict ={'field1' : 1, 'field2':2,}

In [6]: model2, created = models.Model2.objects.update_or_create(model=m1, defaults=datadict)

In [7]: model2, created
Out[7]: (<Model2: Model2 object>, True)

In [8]: models.Model2.objects.get().field1, models.Model2.objects.get().field2
Out[8]: (u'1', u'2')

In [9]: datadict ={'field1' : 3, 'field2':4}

In [10]: model2, created = models.Model2.objects.update_or_create(model=m1, defaults=datadict)

In [11]: model2, created
Out[11]: (<Model2: Model2 object>, False)

In [12]: models.Model2.objects.get().field1, models.Model2.objects.get().field2
Out[12]: (u'3', u'4')

In [13]: models.Model2.objects.get().model.id
Out[13]: 1

In [14]: models.Model1.objects.get().id
Out[14]: 1