首页 > 解决方案 > Django Passing Through List Items

问题描述

I have a todo website that allows users to put a remind in a certain list, such as work, school, groceries, etc. However, I'm a bit lost on how to get the list name and their items to display.

Models.py:

class RemindList(models.Model):
    parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=50)


class Reminder(models.Model):
    remind_types = [('Regular', 'Regular'), ('Long Term', 'Long Term')]
    title = models.CharField(max_length=100)
    description = models.TextField()  
    remind_time = models.DateTimeField(blank=True) 
    parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    parent_list = models.ForeignKey(RemindList, on_delete=models.CASCADE, null=True)
    type_of_remind = models.CharField(max_length=12, choices=remind_types, default='Regular')
    complete = models.BooleanField(default=False)

Views.py:

@login_required(login_url='/login')
def home(request):
    user = get_object_or_404(User, username=request.user.username)
    context = {
        'events': ToDoItem.objects.filter(parent_user=user),
        'reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Regular'),
        'long_term_reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Long Term'), 
        'remind_list_items': RemindList.objects.filter(parent_user=user),
    }
    return render(request, 'main/home.html', context)

I can pass through the list names, and I planned to just loop through them and add Reminder.objects.filter(parent_user=user, type_of_remind='Regular', parent_list=list_name) to context. However, theres no way to loop through them on the html side (can't do for loop because there are other context types), and you can't filter them on the html side (correct me if I'm wrong). Is there another way to do this?

标签: pythondjango

解决方案


Ok, it took me a few readings, but if what I understand is correct you want to be able to iterate over the ReminderList objects and also list out the Reminder items under each one.

My suggestion would be to add a method to ReminderList that returns the items in that list, you could then do something like this in your template

{% for list in reminder_lists %}
  ... List header stuff goes here ...
  {% for item in list.get_reminder_items %}
     ... Print the item ...
  {% endfor %}
{% endfor %}

(The Django templating language can be a little interesting in that object.identifier can map to either an attribute or an object method - this can be useful for cases like these).


推荐阅读