简体   繁体   中英

Filter subset of a queryset in Django

I have these models:

class Committee(models.Model):
    title = models.CharField("Title",max_length=50,null=False)
    members = models.ManyToManyField(User)

class Meeting(models.Model):
    title = models.CharField("Title",max_length=50,null=False)
    date = models.DateTimeField("Date",null=False)
    committee = models.ForeignKey(Committee, on_delete=models.CASCADE)

And I want my view to return all committees in which the logged user is in, and only the meetings that has already happened. I'm trying this code:

class MeetingsView(generic.ListView):
    template_name = 'meetings/index.html'
    context_object_name = 'committees_list'
    login_required = True

    def get_queryset(self):
        return Committee.objects.filter(members__id=self.request.user.id,meeting__date__lte=timezone.now())

This returns me a queryset excluding the committees which has no meeting before today. What I want is to get all the committees, and the meeting_set to be filtered by the date. Is there another way to do it?

If you want to get only specific meetings, use a prefetch. It will link to all related Committee objects:

def get_queryset(self):
    prefetch = Prefetch('meeting_set', queryset=Meeting.objects.filter(date__lte=timezone.now()), to_attr='past_meetings')
    return Committee.objects.filter(members__id=self.request.user.id).prefetch_related(prefetch)

Then to access the past meetings in the template you use:

{% for committee in committee_list %}
    {{ committee.past_meetings }}
{% endfor %}

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