Reputation: 13881
I've got a question model and mcq choices model which have foreign key to question.
class Question(models.Model):
statement = models.TextField(max_length=1024)
def save(self, *args, **kwargs):
super(Question,self).save(*args,**kwargs)
#ques = Question.objects.get(id = self.id)
f = open('/tmp/prj/log.txt', 'w')
choiceobjs = self.choice_set.all()
if choiceobjs:
f.write("choices found")
else:
f.write("choices not found.. zilch")
f.close()
class Choice(models.Model):
value = models.TextField(max_length=1024)
question = models.ForeignKey(Question)
Now I've overridden the save method of question. Even after the question has been saved, I cannot find choice_set in save method! I always get "choices not found.. zilch" in my logfile.
UPDATE: I'm creating my Question in Admin interface, and 'Choice' objects are being created 'inline'.
So the modified question is - In what sequence do the 'inline' fields/models and the main model get created? How can I delay my check for foreignkey set in save method, such that 'foreignkey_set' becomes visible?
Upvotes: 2
Views: 1857
Reputation: 12214
class Foo(models.Model):
pass
class Bar(models.Model):
foo = models.ForeignKey(Foo)
When using inlines of Bar
in the Foo
admin, Django has to save the Foo
object first, because the Bar
objects need the primary key to reference it in a ForeignKey
:
self.save_model(request, new_object, form, change=False)
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=False)
http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L870
That means when Foo
's save
method is called, the inline Bar
objects haven't been saved yet, and therefore can't be queried. So you need to work around this, if you need to access these objects when a Foo instance was saved in the admin (using Bar inlines).
One possible solution would be to attach to a post_save
signal of Bar
, see which Foo
object it is referencing, and executing the relevant code. But this would trigger on every change, even if no Foo object was created.
Upvotes: 3