我有以下型号:
class BaseAddress(models.Model):
name = models.CharField(max_length=100)
business_name = models.CharField(max_length=100, blank=True, null=True)
address = models.CharField(max_length=100, blank=True, null=True)
address_2 = models.CharField(max_length=100, blank=True, null=True)
address_3 = models.CharField(max_length=100, blank=True, null=True)
city = models.CharField(max_length=100, blank=True, null=True)
state = models.CharField(max_length=2, blank=True, null=True)
zip_code = models.CharField(max_length=10, blank=True, null=True)
phone = models.CharField(max_length=30, blank=True, null=True)
class Meta:
abstract = True
class ProfileBilling(BaseAddress):
profile = models.OneToOneField(
Profile, related_name='billing_info')
class OrderBilling(BaseAddress):
order = models.OneToOneField(Order, related_name='billing')
name_on_card = models.CharField(max_length=100)
#card_type = models.PositiveSmallIntegerField(
# choices=CARD_TYPE, default=0)
#card_number = models.CharField(
# max_length=16, default=0)
expire_month = models.PositiveSmallIntegerField(
choices=MONTHS, null=True, default=0)
expire_year = models.PositiveSmallIntegerField(
choices=YEARS, null=True, default=1960)
当客户输入帐单邮寄地址时,我想将其保存在OrderBilling中,但我还想将其保存在ProfileBilling中作为其最新的帐单邮寄地址。我该怎么做?
当OrderBilling和ProfileBilling具有大部分相同的字段时,如何使用表单在两个不同的表中保存帐单邮寄地址...?
我如何在Django中执行此操作?
这是我的OrderBilling表单:
class OrderBillingForm(forms.ModelForm):
class Meta:
model = OrderBilling
exclude = ('order',)
def __init__(self, *args, **kwargs):
super(OrderBillingForm, self).__init__(*args, **kwargs)
self.fields['address'].required = True
self.fields['city'].required = True
self.fields['state'] = USStateField()
self.fields['zip_code'] = us.USZipCodeField()
self.fields['phone'].required = False
self.fields['expire_month'].required = False
self.fields['expire_year'].required = False
def clean(self):
return self.cleaned_data
答案 0 :(得分:0)
您可以覆盖save()
方法,但在您的情况下,更明智的方法是使用post_save
信号来实现此目的。
保存OrderBilling
后,您也可以将其数据保存到ProfileBilling
。
在google搜索中查看一些示例,以便熟悉post_save信号,
像:
然后Easywise在你的post_save接收器| callback funcstion获取OrderBilling
实例
orderbil_instance = kwargs['instance']
并从其数据
创建您的ProfileBillingProfileBilling.objects.create(name=orderbil_instance.name, ....)
类似于post_save
信号接收器
def do_something(sender, **kwargs):
# Getting OrderBilling instance which get saved just now
orderbil_instance = kwargs['instance']
# Save the data into new ProfileBilling
ProfileBilling.objects.create(name=orderbil_instance.name, ....)