我有三个通过外键链接的模型(Guest,Item,Order(FK Item,FK Guest))。现在我想编写一个视图,显示模型中的来宾详细信息和一个表格视图,列出所有未付款状态的订单。
我做的第一部分是这样的。但是我如何才能获得订单?
@login_required
def guest_detail(request, pk):
guest = get_object_or_404(Guest, pk=pk)
if request.method == "POST":
form = RegisterGuestForm(request.POST, instance=guest)
if form.is_valid():
guest = form.save(commit=False)
guest.save()
#post.published_date = timezone.now()
return redirect('guest_detail', pk=guest.pk)
else:
form = RegisterGuestForm(instance=guest)
context = {'form': form}
return render(request, 'hotel/register_guest.html', context)
订单模型如下所示:
class Order(models.Model):
guest = models.ForeignKey('hotel.Guest', on_delete=models.CASCADE)
amount = models.IntegerField(default=1)
item = models.ForeignKey('hotel.Item', on_delete=models.CASCADE)
price = models.IntegerField()
is_paid = models.BooleanField(default=False)
class Meta:
ordering = ['guest']
def __str__(self):
return "{} x {}".format(self.amount, self.item)
答案 0 :(得分:1)
guest = get_object_or_404(Guest, pk=pk)
# The 404 will catch any bad requests
orders = Order.objects.filter(guest = guest, is_paid=False)
context = {'form': form}
context['orders'] = orders
请记住将其添加到您的上下文中,然后您可以在模板中访问它
答案 1 :(得分:0)
默认情况下,您可以通过外键获取订单(如果未通过related_name设置):
guest.order_set.objects
答案 2 :(得分:0)
我认为您需要从给定<GridView
...
android:clipToPadding="false"
android:scrollbarStyle="outsideOverlay" />
查询Order
个实例,请检查我的帮助您:
Guest
这将检索您想要的订单列表