class Customer(models.Model):
customer_id = models.AutoField( primary_key=True)
customer_name = models.TextField()
billing_address = models.ForeignKey(Address,on_delete=models.CASCADE,related_name='Billing')
shipping_address = models.ForeignKey(Address,on_delete=models.CASCADE,related_name='Shipping')
class Address(models.Model):
address_id = models.AutoField(primary_key=True)
address = models.CharField(max_length=200, blank=True)
city= models.CharField(max_length=200, blank=True)
现在,我的问题是我有一个客户模型和地址模型,客户有一个帐单地址和送货地址,而客户有一个地址外键。但是地址模型没有客户外键(如果地址有客户外键我自己也可以这样做。)
在创建客户时,用户必须输入帐单邮寄地址和送货地址。我怎么能这样做?
答案 0 :(得分:0)
您需要将Address模型中的ForeignKey设置为Customer ..并且您可以添加address_type选项字段以指示开票/发货。
class Customer(models.Model):
customer_id = models.AutoField( primary_key=True)
customer_name = models.TextField()
class Address(models.Model):
BILLING='B'
SHIPPING='S'
ADDRESS_TYPE=((BILLING,'Billing'),(SHIPPING,'Shipping'))
address_type=models.CharField(max_length=1, choices=ADDRESS_TYPE, verbose_name="address_type")
customer=models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='addresses', null=False)
address_id = models.AutoField(primary_key=True)
address = models.CharField(max_length=200, blank=True)
city= models.CharField(max_length=200, blank=True)
然后创建inlineformset,如
AddressInlineFormSet = inlineformset_factory(Customer, Address, can_delete=False)