【发布时间】:2016-04-02 19:46:01
【问题描述】:
我正在将 Python + MongoDB (MongoEngine) 用于一个基于预订的简单应用程序。
该应用程序有两个模型:餐厅和预订。
class Restaurant(Document):
name = StringField(max_length=200, required=True)
location = StringField(max_length=200, required=True)
class Reservation(Document):
restaurant_id = ReferenceField(Restaurant, reverse_delete_rule=CASCADE)
time = IntField(min_value=1, required = True)
number_of_people = IntField(min_value=1, required = True)
Reservations 有一个指向餐厅的 ReferenceField。 [MongoEngine 在内部使用 DBRef]
现在,当我渲染餐厅列表时,我必须提供与每家餐厅相对应的预订选项。在与 List of Restaurants 对应的 Django 模板中,我已经包含了餐厅元素的所有三个字段:restaurant.id restaurant.name 和 restaurant.location。
以下是餐厅列表对应的模板。
{% extends "base.html" %}
{% block content %}
{% for restaurant in restaurant_list %}
<div style="margin-bottom: 20px;">
<h4>{{ restaurant.name }}</h4>
<h4>{{ restaurant.location }}</h4>
<a href="{{ restaurant.get_reserve_url }}" class="btn btn-small">Reserve Table</a>
</div>
{% endfor %}
`{% endblock %}
现在如果用户点击保留,我需要创建一个表单(使用 Django 的 CreateView 和 forms.Forms)。
但问题是要保存表单数据(即 MongoDB 的 Reservation 集合中的条目),我需要餐厅的引用对象。我怎样才能得到它?
【问题讨论】:
标签: python django mongodb django-forms django-templates