[Answered ]-Django reverse foreignkey is empty

2👍

Ther eare two possible reasons:

In your add_child method:

That is not your problem, but you can come accross this too

def add_child(self,child):
    child.parent_model = self

you do not save child. So your changes do not reflected to database. But since your querysets are also objects:

>>> foo.add_child(bar)
>>> bar.parent_model
<MyModel: foo>

bar object keeps its new data, but since you did not save it to your database, this do not reflects to foo

You are dealing with out-of-date data:

This is your problem

>>> foo = TestModel(name='foo')
>>> bar = TestModel(name='bar')
>>> foo.save()
>>> bar.save()

You save them and both foo and bar object carry the same values as their relevnt database records.

 >>> foo.add_child(bar)

You update bar object, but do not save it. So each database data are not updated, only bar object is changed.

>>> bar.get_parent()
<TestModel: foo>
>>> foo.get_children()
[]

Your bar object is updated. Since you do not save the changes to your database and refresh related objects (retreive them from the database again) then yould not be updated. So your foo object still out-of-date

You must save the data and retreive required objects from the database again…

>>> foo = TestModel(name='foo')
>>> bar = TestModel(name='bar')
>>> foo.save()
>>> bar.save()  # Instead of make a second save, you can discard this save step and save after `add_child` 
>>> foo.add_child(bar)
>>> bar.save()
>>> foo = MyModel.objects.get(name="foo")
👤Mp0int

Leave a comment