我剛剛開始學習 django 并嘗試使用 manage.py shell 為我的模型中的一對一欄位分配值。我嘗試這樣做,但不確定為什么它沒有將值分配給 Author.address
author1 = Author.objects.get(first_name="Sam")
addr1 = Address.objects.get(post_code="12345")
author1.address = addr1
我錯過了任何遺漏的步驟嗎?
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}"
謝謝
uj5u.com熱心網友回復:
您應該在分配后保存模型
author1 = Author.objects.get(first_name="Sam")
addr1 = Address.objects.get(post_code="12345")
author1.address = addr1
author1.save()
您也可以使用更新方法更新一對一關系
addr1 = Address.objects.get(post_code="12345")
Author.objects.filter(first_name="Sam").update(address=addr1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/404790.html
標籤:
