我扩展了一个模型,但相关模型没有正确保存到数据库中。
下面我只调用SupplyAddress()
而不是通过SupplyAddress.objects.create()
创建并保存它的实例但是,如果我尝试这样做,那么尚未创建相关的地址(和用户)来保存反对。保存用户的最佳方式是Address
和SupplyAddress
?
models.py
class Address(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
house_name_number = models.CharField(max_length=255, verbose_name="house name or number")
street_name = models.CharField(max_length=255)
town_city = models.CharField(max_length=255)
county = models.CharField(max_length=255)
postcode = models.CharField(max_length=8)
time_stamp = models.DateField(auto_now=True)
class SupplyAddress(models.Model):
address = models.OneToOneField(Address)
region = models.ForeignKey(Region, null=True)
occupied = models.BooleanField()
forms.py
class SupplyAddressForm(forms.ModelForm):
occupied = forms.BooleanField()
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
data = self.cleaned_data
supply_address = models.SupplyAddress(
occupied=data['occupied'],
)
self.instance.supplyaddress = supply_address
return self.instance
class Meta:
model = Address
fields = ['house_name_number',
'street_name',
'town_city',
'county',
'same_address',
'move_in_date',
'postcode',
]
views.py
.....
address = form.save(commit=False)
address.user = user
address.save()
答案 0 :(得分:0)
编辑保存方法,
class SupplyAddressForm(forms.ModelForm):
occupied = forms.BooleanField()
class Meta:
model = Address
fields = ['house_name_number',
'street_name',
'town_city',
'county',
'same_address',
'move_in_date',
'postcode',
]
def save(self, *args, **kwargs):
data = self.cleaned_data
supply_address = models.SupplyAddress.objects.create(occupied=data['occupied'])
instance = super(SuppyAddressForm, self).save(*args, **kwargs)
instance.supplyaddress = supply_address
instance.save()
return instance