我试图在Django中保存一对一的关系,但是在保存Address对象之后,它删除了我要与其建立关系的对象上的关系。
在这种情况下,我试图在数据库中已经存在的“ Person”对象与正在创建的“ Address”对象之间建立关系。我可以将Person的address属性分配给新地址,并且该属性在保存之前显示。但是,保存该人后,该人的地址对象消失。我检查以确保我在设置文件中具有正确的MySQL权限,并且可以执行保存新对象所需的所有操作。在数据库中,有一个新的地址条目,但在“人”表中没有与该人条目相关联的地址。我在做什么错了?
if person.address == None:
person.address = managerModels.Addresses()
person.address.zipCode = newAttributeValue # set up zip code
print("Address pre-save {}".format(person.address))
person.address.save()
print("Address post-address save: {}".format(person.address))
person.save()
print("Address post person-save: {} ".format(person.address))
终端上的输出是
Address pre-save None None None None 94536
Address post-address save: None None None None 94536
Address post person-save: None
这是在models.py文件中声明模型的方式。
class Person(models.Model):
userId = models.OneToOneField( settings.AUTH_USER_MODEL, verbose_name = "User account", on_delete=models.DO_NOTHING, null = True)
firstName = models.CharField(max_length=40)
lastName = models.CharField(max_length=40)
phone = models.CharField("Phone Number", max_length=12)
address = models.OneToOneField(Addresses, verbose_name = "Address", on_delete=models.DO_NOTHING, null=True)
tutorType = models.CharField("Category", max_length=12)
gender = models.CharField("Gender", max_length=6)
subjects = models.CharField("Subjects", max_length = 256)
email = models.CharField("Email", max_length = 45, blank = True)
active = models.BooleanField(default = True)
class Meta:
ordering = ('userId', 'firstName', 'lastName', 'phone','tutorType', 'gender', 'subjects')
db_table = 'Persons'
def __str__(self):
return "\n{} {}\nPhone: {}\nAddress:{}\ntutorType: {}\nGender: {}\nsubjects: {}\nemail: {}\nactive {}".format(self.firstName,self.lastName, self.phone, self.address, self.tutorType, self.gender, self.subjects, self.email, self.active)
class Addresses(models.Model):
address1 = models.CharField("Address Line 1", max_length=128, null=True)
address2 = models.CharField("Address Line 2", max_length=128, null=True)
city = models.CharField("City", max_length=64, null=True)
state = models.CharField("State", max_length=64, null = True)
zipCode = models.CharField("Zip Code", max_length=5, null = True)
class Meta:
ordering = ('address1', 'address2', 'city', 'state','zipCode')
db_table = 'Addresses'
def __str__(self):
return "{} {} {} {} {}".format(self.address1, self.address2, self.city, self.state, self.zipCode)
人与地址之间的关系是一对一的。我在做任何明显的错误吗?我已将问题缩小到仅几行代码,但我仍然受困。有什么建议吗?
编辑:我已经更新了代码,因此我仅使用人员地址的一个实例,但是此人上的保存清除了地址数据。还是不知道怎么了。
答案 0 :(得分:0)
在将Address
对象添加到Person
实例之前,应保存该对象。像这样:
address = managerModels.Addresses() # create a new address
address.zipCode = newAttributeValue # set up zip code
address.save()
person.address = address
person.save()