我希望获得给定两个年龄段之间的所有个人资料。示例“从年龄:20岁到30岁” 在我的模型而不是年龄,我保存了用户的出生日期。我需要将出生日期转换为年龄,并希望获得给定年龄之间的配置文件。如果问题不正确,请帮我纠正问题。
models.py
class profiles(models.Model):
user = models.OneToOneField(User)
full_name = models.CharField(max_length=200)
birthday = models.DateField(null=True)
def age(self):
return int((datetime.date.today() - self.birthday).days / 365.25 )
age = property(age)
views.py
def search_results(request):
from_age = form.cleaned_data['from_age']
to_age = form.cleaned_data['to_age']
query_set = profiles.objects.filter(gender=gender)
if from_age < to_age:
query_set = query_set.filter(
age__gte=from_age,
age__lte=to_age
)
答案 0 :(得分:2)
您无法对属性进行过滤。
你应该反过来做:将年龄转换为日期,然后对其进行过滤。
答案 1 :(得分:2)
尝试range查询:
import datetime
def search_results(request):
from_age = form.cleaned_data['from_age']
to_age = form.cleaned_data['to_age']
now = datetime.date.today()
from_date = datetime.date(now.year-int(to_age), now.month, now.day)
to_date = datetime.date(now.year-int(from_age), now.month, now.day)
query_set = profiles.objects.filter(gender=gender,
birthday__range=(from_date, to_date))