﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
8892	ForeignKey relation not saved as expected	Julien Phalip	blacklwhite	"Here are two simple models:

{{{
class ModelA(models.Model):
    name = models.CharField(max_length=10)

class ModelB(models.Model):
    name = models.CharField(max_length=10)
    a = models.ForeignKey(ModelA, blank=True, null=True)
}}}

Now, see the following sequence. When setting the relation *before* saving the related object, the relation itself is not properly saved:

{{{
>>> a = ModelA(name='foo')
>>> b = ModelB(name='bar')
>>> b.a = a # Set relation *before* saving related object
>>> a.save() # Save related object
>>> b.save()
>>> b.a
<ModelA: ModelA object>
>>> b = ModelB.objects.get(name='bar')
>>> b.a
<NoneType: None>
}}}

Logically I'd expect that, since `a` is saved before `b`, the relation would be properly saved but it is not.

Yet, if setting the relation *after* saving the related object, then it works fine (in the below example I only swapped 2 lines: `b.a = a` and `a.save()`):

{{{
>>> a = ModelA(name='foo')
>>> b = ModelB(name='bar')
>>> a.save() # Save related object
>>> b.a = a # Set relation *after* saving related object
>>> b.save()
>>> b.a
<ModelA: ModelA object>
>>> b = ModelB.objects.get(name='bar')
>>> b.a
<ModelA: ModelA object>
}}}

I've tested with MySQL and SQLite."	Bug	closed	Database layer (models, ORM)	1.0	Normal	duplicate		blacklwhite	Accepted	1	0	0	1	0	0
