基本上,我确实没有几个相互引用的模型。 我希望我们之间的关系没问题,但我不是百分百肯定的。 的 models.py
class Table(models.Model):
number = models.IntegerField(unique = True)
isFree = models.BooleanField(default = True)
class MenuItem(models.Model):
name = models.CharField(max_length = 200)
price = models.DecimalField(max_digits=5, decimal_places=2)
quantityInStock = models.PositiveSmallIntegerField(default=10)
class Order(models.Model):
tableFK = models.ForeignKey(Table, on_delete=models.CASCADE)
opened_at = models.DateTimeField('date_created', default = timezone.now)
closed_at = models.DateTimeField('date_closed', blank = True, null = True)
paid = models.BooleanField(default = False)
class Meta:
ordering = ('-opened_at',)
class OrderDetails(models.Model):
STATUS_CHOICES = (
('CHOICE1', 'choice1'),
('CHOICE2', 'choice2'),
('CHOICE3', 'choice3'),
('CHOICE4', 'choice4'),
('CHOICE5', 'choice5')
)
orderFK = models.ForeignKey(Order, on_delete = models.CASCADE)
menuitemFK = models.ForeignKey(MenuItem, on_delete = models.CASCADE)
quantity = models.PositiveSmallIntegerField(default = 1)
status = models.CharField(max_length=5, choices= STATUS_CHOICES, default='choice1')
views.py
def index(request):
orders = Order.objects.select_related("tableFK").filter(paid=False)
template = loader.get_template('autowaiter/index.html')
context = {
'orders':orders
}
return HttpResponse(template.render(context))
我现在所取得的成就是,我确实拥有Orders对象。但在index.html中我想显示如下内容:
请你指出我缺乏的例子和理论吗?
答案 0 :(得分:0)
如果您还没有,请尝试django_tables2,可以生成HTML表格,并使用超链接的列按照新密钥或新表格的外键进行呈现。
答案 1 :(得分:0)
假设我已经理解了您正在寻找的内容,那么基于您当前模型结构的非常简单的模板可能如下所示:
{% for table in tables %}
<h3>Table {{ table.number }}</h3>
<p>Order opened at {{ table.orders.earliest.opened_at }}</p>
{% for orderdetail in table.orders.earliest.orderdetails.all %}
Status: {{ orderdetail.status }}, Quantity: {{ orderdetail.quantity }}
</br>
{% endfor %}
<hr/>
{% endfor %}
但是您需要对模型进行一些调整以支持这一点,即在related_name
中的外键字段中添加Order
属性:
tableFK = models.ForeignKey(Table, related_name='orders', on_delete=models.CASCADE)
和OrderDetail
:
orderFK = models.ForeignKey(Order, related_name='orderdetails', on_delete = models.CASCADE)
以及向get_latest_by
中的Meta
类添加Order
属性:
class Meta:
ordering = ('-opened_at',)
get_latest_by = 'opened_at'
(支持使用earliest
)。
最后,您视图中的查询需要查询具有未付订单的顶级Table
对象,而不是查询订单本身:
def index(request):
# Query the tables with unpaid orders
tables = Table.objects.filter(orders__paid=False)
template = loader.get_template('autowaiter/index.html')
context = {
'tables': tables
}
return HttpResponse(template.render(context))