简体   繁体   English

如何根据model.django中的charfield选项过滤用户

[英]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? 我是否必须在views.py中创建if语句或for循环? or do i use aq lookup? 还是我使用aq查找? 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. 建议在视图中过滤结果,根据您的要求,您可以只使用本机django查询集。 You can create a view like this: 您可以创建如下视图:

views.py 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 因此,例如,如果您有一个用于列出用户的url /users/ ,则传递location参数将过滤您的用户/users/?location=london

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM