我正在尝试制作一个简单的搜索功能。我正在使用User
模型和具有OneToOne关系的UserProfile
模型。我已成功设法通过用户名,名字和姓氏进行搜索,所有三个字段都在User
模型中。但是,我想根据UserProfile
模型中的字段进行过滤,例如性别,年龄,地点等。
views.py
def Home(request):
query = request.GET.get('query', '')
queryset = User.objects.none()
if request.method == "GET":
form = SearchForm(request.GET)
if form.is_valid():
if query != '':
queryset = User.objects.filter(Q(username__icontains=query)
| Q(first_name__icontains=query)
| Q(last_name__icontains=query)).exclude(is_staff=True)
else:
form = SearchForm()
return render(request, "main/home.html", {'form': form, 'queryset': queryset})
home.html的
{% extends "base.html" %}
{% block body %}
<h3>Home</h3>
<p>
<form method="get" action="">
{{ form.as_p }}
<input type="submit" value="Search"/>
</form>
</p>
<p>
{% for user in queryset %}
<a href="{% url 'main:profile' user.id %}">{{ user.get_full_name }}</a> <br/>
{% endfor %}
</p>
{% endblock %}
forms.py
class SearchForm(forms.Form):
query = forms.CharField(max_length=100, label="", widget=forms.TextInput(attrs={'placeholder': 'Search...'}), required=False)
age_from = forms.IntegerField(label="", widget=forms.NumberInput(attrs={'placeholder': 'Age from'}), required=False)
age_to = forms.IntegerField(label="", widget=forms.NumberInput(attrs={'placeholder': 'Age to'}), required=False)
models.py
UserProfile(models.Model):
sex_choices = (
('Male', 'Male'),
('Female', 'Female'),
('Other', 'Other'),
)
sex = models.CharField(max_length=6,
choices=sex_choices,
default='Male')
birth_date = models.DateField()
如何根据与UserProfile
模型具有OneToOne关系的User
模型上的其他字段添加搜索选项?
答案 0 :(得分:2)
您需要使用相关名称。
由于您还没有分享您的模型定义,我们假设:
class UserProfile(models.Model):
user = models.OneToOneField(User)
sex = models.CharField(...)
...
所以,当你查询:
User.objects.filter(user_profile_set__sex='female')
修改强>
要根据年龄进行查询,假设您在表单中询问“年龄”并将生日存储在模型中,您可以尝试这样的事情:
from datetime import datetime
age = 18 # this shoudl come from form
birth_year = datetime.now().year - age
User.objects.filter(user_profile_set__birth_date__year=birth_year)