简体   繁体   中英

Django Query for two related models

I have an Order model that is related to Booking model as ForeignKey field. So, an Order can be related to multiple Booking objects.

class Order(models.Model):
    shop=models.ForeignKey(Shop, on_delete=models.CASCADE, blank=True, null=True)
    user=models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, blank=True, null=True)
    order_id=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4)
    order_date=models.DateField(default=date.today)

class Booking(models.Model):
    order=models.ForeignKey(Order, on_delete=models.CASCADE, blank=True, null=True)
    service=models.ForeignKey(Service, on_delete=models.CASCADE, blank=True, null = True)

My goal is to show Order with the related Booking objects like this:

<ul>
{% for order in orders %}
    <li>{{ order.order_id }}</li>
    <ul>
         {% for booking in BOOKINGS WITH THIS ORDER ID %}
         <li>{{ booking.service }}</li>
         {% endfor %}
    </ul>
{% endfor %}
</ul>

In the template, with in each order, I want to be able to loop through bookings with that order id.

I am having trouble figuring out how to make the proper query to achieve that in the template.

I thought about creating a dictionary object to store and pass the related booking object details, but this does not seem to be the proper way to do this.

def shopDashboardPastBookings(request):
    orders = Order.objects.filter(shop_id = shopID ).exclude(order_date__gte = (datetime.now() - timedelta(days=1)) )
    bookings = {}
    for order in orders:
        booking_query = Booking.filter(order = order )
        bookings[order.order_id] = booking_query 

    // should I be making separate queries for each orders like this?

    paginator = Paginator(orders, 10)
    page = request.GET.get('page')
    paged_orders = paginator.get_page(page)
    context = {
    'orders':paged_orders,
    'bookings':bookings,
    }
    return render(request, 'dashboard-pastbookings.html',context)

Firstly, prefetch orders' bookings in the initial query in order to save db hits:

orders = Order.objects.filter(...).exclude(...).prefetch_related('booking_set')

There shouldn't be a need to retrieve bookings to a separate context variable in the view. Then, in the template, just access a specific order's bookings via the FK's default related_name :

{% for booking in order.booking_set.all %}  

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