如何在django中创建更好的模型

时间:2013-02-20 21:12:10

标签: django django-models

我有两个模型OrderOrderitem Order收集客户信息并跟踪客户订购的状态。

class Order(SmartModel):
    #each individual status
    SUBMITTED = 1 # the credit card was valid or mobilemoney was recieved.It is ready for us to process the order
    PROCESSED = 2 # After submitted orders are reviewed, we can mark them as processed, letting deliverers know order is ready to be shipped
    DELIVERED = 3 # the order has been processed and approved by the adminstrator(in this case us), it can delivered.
    CANCELLED = 4 # Customer called the company and decided they didnt want to go through with the order either by phone or email.

    # SET OF POSSIBLE STATUSES
    ORDER_STATUSES = ((SUBMITTED,'Submitted'),(PROCESSED,'Processed'),(DELIVERED,'Delivered'),(CANCELLED,'Cancelled'),)
    #Order info
    date = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=ORDER_STATUSES, default=SUBMITTED)
    last_updated = models.DateTimeField(auto_now=True)
#   transaction_id = models.CharField(max_length=20)

    #contact info
    email = models.EmailField(max_length=50)
    phone = PhoneNumberField(max_length=20,default='+250785559899')

    #delivery information
    delivery_name = models.CharField(max_length=50)
    delivery_city = models.CharField(max_length = 50)
    delivery_address = models.CharField(max_length=50,help_text="e.g Klab 6th floor,Telecomhouse,Kacyiru")
    restaurant = models.ForeignKey(Restaurant,default='1')

OrderItem在另一方持有物品和数量

class OrderItem(SmartModel):
    shopping_id = models.CharField(max_length=50,db_index=True)
    quantity = models.IntegerField(default=0)
    item = models.ForeignKey(Item)
    order = models.ForeignKey(Order)
我正在创建这样的模型。

try:
   order= Order.objects.get(pk=order_id)
   restaurant = Restaurant.objects.get(pk=restaurant_id)
except:
   order = Order(created_by=anon_user,modified_by=anon_user)
   order.save()
   oi=OrderItem(order=order,shopping_id=_shopping_id(request),
                                          quantity=quantity,
                                          item=i,
                                          created_by=anon_user,
                                          modified_by=anon_user)
   oi.save()

现在,您在OrderItem中看到我包含了一个外键order,这是因为我希望能够拥有一个包含订单商品,数量和{{1}的模型}} 细节。但这不起作用我得到一个无类型错误,Order

我需要帮助,了解我如何才能使这项工作。

coercing to Unicode: need string or buffer, NoneType found

1 个答案:

答案 0 :(得分:0)

首先,您应该始终调试代码并找到出现错误的位置。

我认为这方面存在一些问题:

order = Order(created_by=anon_user,modified_by=anon_user)
order.save()

因为您尝试创建并保存模型实例而没有所有必填字段(例如电子邮件字段)