我正在尝试拆分现有的模型类。原始类不是最佳的,因此我想将CustomerOrder中的所有客户相关信息移动到新的Customer类中。在Django中执行此操作的最佳方法是什么?
旧模型类:
class CustomerOrder(models.Model):
# Customer information fields
first_name = models.CharField(max_length=200) # Customer first name
last_name = models.CharField(max_length=200) # Customer last name
email = models.EmailField() # Customer email address
address = models.CharField(max_length=255) # Address to deliver (e.g. 1532 Commonwealth St. Apt 302)
city = models.CharField(max_length=200) # City to deliver (e.g. Fullerton, CA 92014)
# Order information fields
note = models.TextField() # Any notes the customer may have about shipping
shipping_method = models.CharField(max_length=200) # Shipping in LA or OC
total_price = models.FloatField(default=0) # Total price of the order
delivery_date = models.DateField() # When to deliver the order. Order is "live" until the next
# day after delivery. So if delivery date is Jan 3, it's "live" until Jan 4.
order_date = models.DateField() # When the customer ordered
time_slot = models.CharField(max_length=200) # What time to deliver the product
is_cancelled = models.BooleanField(default=False) # If the order is cancelled or refunded, we mark it here.
created_at = models.DateTimeField(auto_now_add=True) # When the order entry was saved into database
updated_at = models.DateTimeField(auto_now=True) # When the order was last updated in database
def __str__(self):
return self.first_name + " " + self.last_name
新模型类:
class Customer(models.Model):
first_name = models.CharField(max_length=200) # Customer first name
last_name = models.CharField(max_length=200) # Customer last name
email = models.EmailField() # Customer email address
address = models.CharField(max_length=255) # Address to deliver (e.g. 1532 Commonwealth St. Apt 302)
city = models.CharField(max_length=200) # City to deliver (e.g. Fullerton, CA 92014)
旧模型中有重复项,所以我也希望删除它们。
答案 0 :(得分:0)
这取决于您的数据库类型。 read this
你应该小心不要丢失数据!
答案 1 :(得分:0)
我认为问题更多地与整个关系数据库架构有关。
我会将所有与客户相关的内容放在一个表中,就像您拥有的新CustomerOrder(重命名为Customer)类一样,然后为Orders创建另一个类,然后将这两个类链接为一对多关系。例如,一个客户可以下多个订单。如果要实现这一对多关系,只需将以下内容添加到订单类:
{{1}}
现在,当您创建新订单实例时,您可以分配客户。 附:反向访问,即从客户订购,你基本上做customer.order_set()方法(客户可以下多个订单)。