LearningNoob
LearningNoob

Reputation: 700

how to update with a foreign key field that also has a foreign key field

I have three sample models below:

Class User(Model):
    ...some other fields
    receiving_info = OnetoOneField('ReceivingInfo')

Class ReceivingInfo(Model):
    ...other fields
    receiving_address = OnetoOneField('Address')
    
Class Address(Model):
    street = CharField(max_length=100)
    house_number = CharField(max_length=100)
    city = CharField(max_length=200)

I am trying to update them below using this:

address = Address(
   street='new st',
   house_number='new number',
   city='new city'
)

user = User.objects.get(id=id)
user.receiving_info.receiving_address = address
user.save()

but somehow it doesn't work, any ideas how to make it work?

Upvotes: 1

Views: 37

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You need to save the address first, otherwise it has no primary key, and you thus can not link to it:

address = Address(
   street='new st',
   house_number='new number',
   city='new city'
)
address.save()

user = User.objects.get(id=id)
receiving_info = user.receiving_info
receiving_info.receiving_address = address
receiving_info.save()

You should also save the receiving_info object, not the user, since that object remains unchanged.

You can however make this more efficient, and reduce the number of queries with one by retrieving the ReceivingInfo directly:

address = Address.objects.create(
   street='new st',
   house_number='new number',
   city='new city'
)

receiving_info = ReceivingInfo.objects.get(user__id=id)
receiving_info.receiving_address = address
receiving_info.save()

I'm also not entirely sure why you have a ReceivingInfo model in the first place. It looks like it has not much "added value", and it only makes querying more complicated. If it thus only groups some info, it still might be better to save this under the User model.

Upvotes: 1

Related Questions