'How To Use Reverse Relations in Django Class Based Views - 2

I'm creating a to-do list where I want the tasks to get displayed on its respective date, but I'm having a hard time doing so.

I found another resource that kind of answered a similar question, but I'm still having a hard time implementing the query with reverse relations, and not quite sure how to put it on template.

link

Been spending 2 or 3 days stuck on this. Hope I could get some pointers here

Desired Outcome

Current Outcome

My models:

class Dailies(models.Model):

    date = models.DateField(auto_now_add=True)

    the_user = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return str(self.date)

class DailyTask(models.Model):
    task = models.CharField(max_length=255)
    dailies = models.ForeignKey(
        Dailies,
        on_delete=models.CASCADE
    )

    def __str__(self):
        return self.task

My ListView:

class DailiesListView(LoginRequiredMixin, ListView):
    model = Dailies

    template_name = 'home.html'

    context_object_name = 'date'

    ordering = ['-date']

    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['date'] = context['date'].filter(the_user=self.request.user)
        context['todos'] = DailyTask.objects.filter(
            dailies__the_user=self.request.user)

        return context

My template (home.html):

{% if user.is_authenticated %}
    
    {% for each_date in date %}
    <h3>
        <li>
            {{each_date}}: 
            {% for todo in todos %} 
                {{todo}}
            {% endfor %}
        </li>  
    </h3>   
    {% endfor %}

{% else %}
    ...
{% endif %}


Solution 1:[1]

By using {% for todo in each_date.dailytask_set.all %}, it allowed me to iterate correctly.

What I did is that I used RelatedManager by using "_set", and it allowed me to trace back to dailytask and iterate out the tasks that corresponds to their dates. And that gave me the desired outcome.

Thankyou @mirodil for helping out!

Solution 2:[2]

In your template {% for todo in date.dailies_set.all %} you're getting dailies from date which always retrieve all dates, but you should try to get it from each_date, so your code should be like that.

{% if user.is_authenticated %}
    
    {% for each_date in date %}
    <h3>
        <li>
            {{each_date}}: 
            {% for todo in each_date.dailies_set.all %}
                <br>
                {{todo}}
            {% endfor %}
        </li>  
    </h3>   
    {% endfor %}

{% else %}
    ...
{% endif %}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ouflak
Solution 2 mirodil