![](/img/trans.png)
[英]How to set a variable from one class equals to a variable in another class in Django models.py?
[英]django models.py - migrating from one model class to another
我正在嘗試分解現有的模型類。 原始類不是最佳選擇,因此我想將所有與客戶相關的信息從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)
在舊模型中有重復項,因此我也希望將其刪除。
這取決於您的數據庫類型。 讀這個
您應該小心不要丟失數據!
我認為問題更多與整個關系數據庫架構有關。
我會將所有與客戶相關的東西都放在一個表中,就像您擁有的新CustomerOrder(將其重命名為Customer)類一樣,然后為Orders創建另一個類,然后將它們與一對多關系鏈接起來。 例如,一個客戶可以下很多訂單。 如果要實現這種一對多關系,只需將以下內容添加到訂單類:
class Order(models.Model):
# The relavant order fields which you require, i.e. order number etc.
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
現在,當您創建新的訂單實例時,您可以分配客戶。 ps可以反向訪問,即從客戶到訂單,您基本上可以使用customer.order_set()方法(客戶可以下很多訂單)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.