Django 如何实现更复杂的过滤器?
我试图根据特定条件查询用户子集。按大多数条件进行过滤相对简单,但有些条件更复杂。例如,我正在尝试将一个函数合并到查询筛选器中:Django 如何实现更复杂的过滤器?,django,django-models,django-views,Django,Django Models,Django Views,我试图根据特定条件查询用户子集。按大多数条件进行过滤相对简单,但有些条件更复杂。例如,我正在尝试将一个函数合并到查询筛选器中: def prefs_are_none(profile): none = True if profile.get_faves() or profile.get_choices(): none = False return none 我不确定如何将该功能添加到此查询中: user_list = Profile.objects.a
def prefs_are_none(profile):
none = True
if profile.get_faves() or profile.get_choices():
none = False
return none
我不确定如何将该功能添加到此查询中:
user_list = Profile.objects.annotate(
distance_away=Distance(
'last_location', current_user.last_location
)
).filter(last_location__distance_lte=(
current_user.last_location, D(km=200)
), public=True, # additional filters would ideally go here)
下面是概要文件的模型,它清除了上面使用的某些方法(get_faves(),get_choices()):
因此,本质上,在我试图通过get\u faves()
和get\u choices()
函数检查的查询中,配置文件既没有空的,也没有空的,这就是prefs\u are\u none()
函数中当前发生的情况。
如何将所有这些功能合并到查询中 您需要在queryset中实现或条件。您可以通过以下方式执行此操作:
在本例中,Q
与|
连接的对象将向查询添加或
条件
class Profile(models.Model):
fave1 = models.CharField(max_length=54, blank=True, null=True,
verbose_name='Learn A')
fave2 = models.CharField(max_length=54, blank=True, null=True,
verbose_name='Learn B')
choice1 = models.CharField(max_length=54, blank=True, null=True,
verbose_name='Teach A')
choice2 = models.CharField(max_length=54, blank=True, null=True,
verbose_name='Teach B')
public = models.BooleanField(default=False, verbose_name='Public')
last_location = models.PointField(null=True)
objects = ProfileManager()
def __str__(self):
return self.user.username
def get_faves(self):
list_of_faves = [self.fave1, self.fave2]
return [field for field in list_of_faves if field]
def get_choices(self):
list_of_choices = [self.choice1, self.choice2]
return [field for field in list_of_choices if field]
from django.db.models import Q
Profile.objects.filter(
Q(fave1__isnull=False) | Q(fave2__isnull=False),
Q(choice1__isnull=False) | Q(choice1__isnull=False),
last_location__distance_lte=(current_user.last_location, D(km=200)),
public=True
)