在Django中保存外键对象

时间:2009-10-12 11:22:36

标签: django django-models

我完全不知道为什么这不起作用:

flight = Flight.objects.get(pk=flight_id)
print "old", flight.route.pk ## `route` is a ForeignKey field to model Route
print "new", new_route.pk
flight.route=new_route  # new_route is a newly created Route object
flight.save()
print "db", Flight.objects.get(pk=flight_id).route.pk

这是输出:

old 4800
new 7617
db 4800

我需要在飞机上调用save()以实际保存吗?

编辑:我的模型看起来像这样:

class Flight(models.Model):
    route = models.ForeignKey(Route, blank=True, null=True, related_name="flight")

class Route(models.model):
    # a bunch of CharFields and IntegerFields

2 个答案:

答案 0 :(得分:1)

new_route已保存吗?假设pk不会返回结果,但无法测试。

否则请参阅http://code.djangoproject.com/ticket/8892

答案 1 :(得分:0)

好的,我刚刚弄明白,我最近将自定义保存功能从类定义的底部移到了顶部,我忘记了调用super(Flight, self).save(*args, **kwargs)的最后一行