在DetailView中显示多个对象

时间:2016-04-05 02:53:55

标签: python django django-views

我最近一直在涉及Django CBV并且有一个问题。也许你有比我更好的想法。

假设我有一家航空公司预订CRM应用程序,我打算为各种事情显示客户。假设我有Models的列表,CustomerBookingRatingCustomer_Service_CallsFavourited_Route

现在,鉴于Django的CBV实现DetailView,我有类似的东西

class CustomerThreeSixtyView(DetailView):
  model = 'Customer'

  def get_context_data(self, **kwargs):
      context = super(CustomerThreeSixtyView, self).get_context_data(**kwargs)
      context['bookings'] = Booking.objects.all.filter(customer_id=request.kwargs['pk']
      context['ratings'] = Ratings.objects.all.filter(customer_id=request.kwargs['pk']
      context['calls'] = Customer_Service_Calls.objects.all.filter(customer_id=request.kwargs['pk'], status'Open')
      context['fav_routes'] = Favourited_Route.objects.all.filter(customer_id=request.kwargs['pk'], status'Open')
      return context

像这样的东西。我的问题是,有没有更好的方法来做到这一点?这是最直接的方式,但我正在寻求建议,因为似乎有某种限制。

1 个答案:

答案 0 :(得分:3)

你所做的已经看起来很好了。您将在上下文中获得所需内容,然后在模板中使用它来显示信息。

或者,您可以直接访问模板中特定客户的预订,而无需在上下文中指定:

{% for booking in object.booking_set.all %} # object is the customer here
     # do what you want to do with the booking here
{% endfor %}

如果您在将客户链接到预订时使用related_name会更好:

class Booking(models.Model):
    customer = models.ForeignKey(Customer, related_name='bookings')
    # other fields

现在,您可以直接使用定义的related_name来访问特定客户的预订:

{% for booking in object.bookings.all %}
     # do what you want to do with the booking here
{% endfor %}

并且,您可以对其他类使用相同的方法,例如RatingCustomer_Service_CallsFavourited_Route等。