How to filter a Generic ListView?

久未见 提交于 2021-02-10 16:48:54

问题


I am using a CBV ListView, The problem is, the view returns a list of ALL notes on the system. What I would really prefer is for the list to only return the 'notes' that are associated with a particular CandProfile (model)

The notes model is :

class CandidateNote(models.Model):

  candidate   = models.ForeignKey(CandProfile, on_delete=models.CASCADE, related_name='candidatenotes_cand')
  note_by     = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name='candidatenotes_user')
  job_note    = models.TextField(max_length=3000)
  date_added  = models.DateTimeField(auto_now_add=True)

I am new to Django and querying, and don't really know how to approach this in a Class based view....my initial thoughts were : Maybe I should modify the get_queryset method.

Any help will be greatly appreciated.


回答1:


In views.py,

class UserNote(generic.ListView):
     template_name = **add your template name here **
     context_object_name = 'user_notes'

     def get_queryset(self):
          return CandidateNote.objects.filter(user__username=self.kwargs['username'])

You can show it on html, {% for notes in user_notes %} ** your template ** {% endfor %}



来源:https://stackoverflow.com/questions/52510586/how-to-filter-a-generic-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!