簡體   English   中英

如何根據model.django中的charfield選項過濾用戶

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

因此,我目前將此作為每個用戶的個人資料模型。

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)

我如何根據位置字段中給出的選擇來過濾用戶? 因此,例如,如果當前用戶已選擇倫敦,則在模板中,他們將僅看到具有相同位置的用戶/配置文件的結果。

我是否必須在views.py中創建if語句或for循環? 還是我使用aq查找? 如果有人可以給我一些指導或向我展示正確的方向,那就太好了!

預先感謝您的任何幫助

建議在視圖中過濾結果,根據您的要求,您可以只使用本機django查詢集。 您可以創建如下視圖:

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})

因此,例如,如果您有一個用於列出用戶的url /users/ ,則傳遞location參數將過濾您的用戶/users/?location=london

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM