0

我有以下型号:

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
4

1 回答 1

0

您可以覆盖save()方法,但在您的情况下更聪明的方法是post_save为此目的使用信号。

保存后OrderBilling,您也可以将其数据保存到ProfileBilling

如果熟悉 post_save 信号,请查看谷歌搜索的一些示例,

喜欢:

然后在您的 post_save 接收器|回调函数中轻松获取OrderBilling实例

orderbil_instance = kwargs['instance']

并根据其数据创建您的 ProfileBilling

ProfileBilling.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, ....)
于 2013-03-26T18:28:10.690 回答