0

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)

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

that was helpful. Thank you. Could you maybe explain me the context['orders']=orders doest it simply end up meaning context['orders']=Order.objects.filter(guest = guest, is_paid=False)?
IMO It's just a slightly more readable version. It does exactly the same.
0

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

Good luck!

Comments

0

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

1 Comment

then you can access every order individually in for loop as QuerySet is iterable (list like)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.