简体   繁体   中英

How to filter users depending on a models.charfield choices in django

so i currently have this as my profile model for each user.

class Profile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=120, choices=LOCATIONS,null=True, blank=True)
picture = models.ImageField(upload_to=upload_location, null=True, blank=True)

how to i filer users depending on the choices given in the location field? So for example if the current user has London selected, in the template they will only see results of users/profiles with the same location.

Do i have to create an if statement or a for loop in the views.py? or do i use aq lookup? if anyone could give me some pointers or show me in the right direction that would be amazing!

thank you for any help in advance

It is recommended to filter the results in the view and based on your requirement, you can just use the native django queryset. You can create a view like this:

views.py

from django.contrib.auth.models import User
from django.shortcuts import render

def users(request):
    location = request.GET.get('location', 'default_location')
    users = User.objects.filter(profile__location=location)
    return render(request, 'users.html', {'users': users})

So for example if you have a url /users/ for listing the users, passing the location parameter will filter your users /users/?location=london

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