Рендеринг объектов из двух запросов в один для l oop в Django - PullRequest
0 голосов
/ 29 марта 2020

Я пытаюсь получить объекты из двух разных запросов, используя select_related (), чтобы получить все связанные объекты.

В шаблоне я использую For l oop, чтобы отобразить все объекты первой модели отдельно, как отдельные контейнеры данных.

Внутри каждого из этих визуализированных объектов первой модели мне нужно показать соответствующие данные из обоих запросов для связанной второй модели.

Проблема в том, что, когда я использую For l oop в шаблоне, я могу получить только объекты для первого связанного запроса, но не для второго запроса, который также связан с первой моделью (в основном, какая вторая запрос делает получение всех объектов, основанных на дате меньше, чем сегодня.)

Вот код:

# IN THE MODELS

class BillType(models.Model):
    name = models.CharField(max_length=200)
    created_on = models.DateTimeField(default=datetime.now, blank=True)

    def __str__(self):
        return self.name

class Bill(models.Model):
    bill_type = models.ForeignKey(BillType, on_delete=models.CASCADE, related_name='billtype')
    month = models.CharField(max_length=200)
    amount = models.IntegerField()
    due_date = models.DateField(blank=True)
    note = models.TextField(blank=True)
    recurring = models.BooleanField(default=True)
    currency = models.CharField(max_length=100)
    created_on = models.DateField(default=datetime.now, blank=True)

    def __str__(self):
        return self.month
# IN THE VIEW

# This will get all of the Bill Types needed for For Loop in the template
bill_types = BillType.objects.all()

# This will get all of the Bills related to the Bill Types. I will need this for showing the  
# corresponding Latest Bill in the template, beside the Overdue bill for each the Bill Types
bills = Bill.objects.select_related('bill_type').all()

# This need to get all of the Bills that are older than 'today'
today = datetime.today()
overdue = Bill.objects.select_related('bill_type').filter(due_date__lte=today).values()
# IN THE TEMPLATE

# This should loop through Bill Types and render separate <div> containers for each of the existing Bill Types
# I.e there would be two Bill Types such as Electricity and Water. This code should generate two separate containers
# that will show the corresponding Overdue bills for each of these Bill Types.

{% for bt in bill_types %}  

...

<div class="bo-widget-bill-cont overdue">
<span class="bo-overdue-warning"><i class="fas fa-exclamation-triangle"></i></span>
  <div class="bo-bill-info">

  # And in the lines below, I will need to Show the Overdue data, related to the bt or bill_types.

  <span>{{ bt.overdue.last.month }}</span>
    <div>
      <span>{{ bt.billtype.overdue.last.amount }}</span> 
      <p>Due Date:{{ overdue.last.due_date }}</p>
    </div>
  </div>
  <div class="bo-bill-actions">
    <a class="bo-bill-paid-action" href="javascript:;"><i class="fas fa-check"></i></a>
  </div>
</div>

...


{% endfor %}

Любая подсказка будет высоко оценена.

Спасибо

...