简体   繁体   中英

Django: using multiple models in one view

I have three models linked via foreign keys (Guest, Item, Order(FK Item, FK Guest)). Now I want to write a view that shows the Guests' Details from the model and a table view listing all his Orders in status unpaid).

The first part I did like this. But how can I get the orders in?

@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)

The Order Model looks like this:

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)
    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

remember to add it to your context and you can access it in the template

you could get the Orders via the foreign key, by default (if not set via related_name): guest.order_set.objects

Good luck!

I think you need to query Order instance from given Guest check this my help you:
orders = Order.objects.filter(guest=guest).all()
this will retrieve list of orders that you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM