I'm just start learning about django and trying to assign value to one-to-one field in my models using manage.py shell. I try to do this way but not sure why it doesn't assign the value to Author.address
author1 = Author.objects.get(first_name="Sam")
addr1 = Address.objects.get(post_code="12345")
author1.address = addr1
Any missing step i missed?
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
address = models.OneToOneField(Address, on_delete=models.CASCADE, null=True)
def full_name(self):
return f"{self.first_name} {self.last_name}"
def __str__(self):
return self.full_name()
class Address(models.Model):
street = models.CharField(max_length=80)
postal_code = models.CharField(max_length=5)
city = models.CharField(max_length=50)
def __str__(self):
return f"{self.street}"
Thanks
CodePudding user response:
You should save the model after assignment
author1 = Author.objects.get(first_name="Sam")
addr1 = Address.objects.get(post_code="12345")
author1.address = addr1
author1.save()
Also you can update 1-to-1 relation with update method
addr1 = Address.objects.get(post_code="12345")
Author.objects.filter(first_name="Sam").update(address=addr1)