0

我有这样的情况:

楷模:

class Test2(models.Model) {
  date = models.DateField(editable=False)
}

class Test(models.Model) {
  test2 = models.ForeignKey(Test2)
}

行动:

for test_obj in Test.objects.all():
  test2_obj = test_obj.test2
  test2_obj.date = date.today()
  test2_obj.save()
  test_obj.save()

在该操作之后,日期test2_obj不会更改。为什么?是test2_obj = test_obj.test2副本吗?

4

1 回答 1

0

我创建 testapp 并测试你的问题

模型.py

from django.db import models

class Test2(models.Model):
    date = models.DateField(editable=False)

class Test(models.Model):
    test2 = models.ForeignKey(Test2)

测试.py

from django.test import TestCase
from models import Test, Test2

from datetime import datetime, date

class SimpleTest(TestCase):
    def test_field_update(self):
        old_date = date(2012,11,11)
        current_date = datetime.today().date()

        t2 = Test2(date = old_date)
        t2.save()

        t1 = Test(test2 = t2)
        t1.save()


        for test_obj in Test.objects.all():
            test2_obj = test_obj.test2
            test2_obj.date = current_date
            test2_obj.save()
            test_obj.save()

        t2 = Test2.objects.all()[0]

        self.assertEqual(t2.date, current_date)

运行测试

.. >manage.py 测试 testapp

为别名“默认”创建测试数据库...。-------------------------------------------------- -------------------- 在 0.016 秒内运行 1 次测试

OK 正在销毁别名“default”的测试数据库...

所以你这是按预期工作,而不是你发布的那样。

于 2012-12-11T13:38:28.193 回答