我有一个模型Order
,
class Order(SmartModel):
date = models.DateTimeField(...)
status = models.IntegerField(...)
restaurant = models.ForeignKey(Restaurant,null=True,blank=True,default = None,help_text="The restaurant the customer order from")
email = models.EmailField(...)
mobile = PhoneNumberField(...)
我正在保存这样的对象,
orders = Order()
checkout_form = forms.CheckoutForm(request.POST,instance=orders)
orders = checkout_form.save(commit=False)
anon_user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
orders.created_by = anon_user
orders.modified_by = anon_user
orders.status = Order.SUBMITTED
orders.save()
你可以看到我没有保存餐厅(fk字段),我该怎么办呢。我看过这个(https://groups.google.com/forum/?fromgroups=#!topic/django-users/PcSDKZhPVmc)和其他几个例子,但是他们让我更加困惑。
我需要绑〜餐馆〜订购,这样当我查询订单时,我知道它属于哪家餐馆。
令人烦恼的是我没有加载djangoproject.com,已经过了一个星期。
forms.py,
class CheckoutForm(forms.ModelForm):
class Meta:
model = Order
exclude = ('created_by','modified_by','is_active','status','restaurant','date')
模板,
<table>
{{ form.errors }}
{{ form.non_field_errors }}
{% form_table_row form.email %}
{% form_table_row form.mobile %}
</table>
答案 0 :(得分:0)
在您的视图中,您需要获取Restaurant
对象并将其保存在order
中。由于您尚未显示完整的视图代码,因此我不确定如何获取Restaurant
对象。
以下是示例代码...
orders = Order()
checkout_form = forms.CheckoutForm(request.POST,instance=orders)
orders = checkout_form.save(commit=False)
#get restaurant obj
restaurant = Restaurant.objects.get(name = "some_restaurant")
orders.restaurant = restaurant
anon_user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
orders.created_by = anon_user
orders.modified_by = anon_user
orders.status = Order.SUBMITTED
orders.save()
答案 1 :(得分:0)
我想我会在这里猜测或创建示例场景:
用户创建信息后,选择他们的餐厅。他们必须进入用户选择订单的下一个表单。餐馆ID必须通过下一个表格,以便当用户提交订单时,我们将使用该餐馆ID保存订单。
def save_order(request, restaurant_id):
anon_user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
orders = Order(restaurant_id=restaurant_id)
checkout_form = forms.CheckoutForm(request.POST, instance=orders)
checkout = checkout_form.save(commit=False)
checkout.created_by = anon_user
checkout.modified_by = anon_user
checkout.status = Order.SUBMITTED
checkout.save()