我使用默认User
模型,Agent
充当OneToOne个人资料模型。我想创建一个包含Agent作为字段的所有用户的查询集。我知道hasattr
但它返回一个True / False布尔值,所以我无法将其实现到我的查询中。
视图
class AgentSearchResults(ListView):
model = User
template_name = 'agent_search_results.html'
def get_queryset(self):
queryset = super(AgentSearchResults, self).get_queryset()
# Write something here to check if all users in 'queryset' has 'agent'.
return queryset
模型供参考
class Agent(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='agent')
答案 0 :(得分:1)
您可以通过检查过滤相关模型的pk为空
User.objects.filter(agent__pk__isnull=False)
对于你的情况:
def get_queryset(self):
queryset = super(AgentSearchResults, self).get_queryset()
# Write something here to check if all users in 'queryset' has 'agent'.
queryset = queryset.filter(agent__pk__isnull=False)
return queryset