0

当我查询 job_seeker 个人资料时,如果没有 job_seeker 数据,则出现错误JobSeeker models query does not exist。如果没有数据,我想传递空列表。为此,我尝试了以下方式,但出现错误,因此无法传递自定义响应

class JobSeekerNode(DjangoObjectType):
    class Meta:
        model = models.JobSeeker
        interfaces = (relay.Node, )

class JobSeekerQueries(ObjectType):
    job_seeker = Field(JobSeekerNode)

    def resolve_job_seeker(self, info, **kwargs):
        data = {}
        if info.context.user.is_authenticated:
            try:
                profile = Profile.objects.get(user=info.context.user)
                try:
                    job_seeker = models.JobSeeker.objects.get(profile=profile)
                    data['job_seeker'] = job_seeker
                except:
                    # when there's no row instead of passing error, pass empty list
                    data['job_seeker'] = []
                return JsonResponse(data)
            except Profile.DoesNotExist:
                return []
        return None

这是我在尝试传递自定义响应时遇到的错误(如果没有数据,则为空列表)

{
  "errors": [
    {
      "message": "Received incompatible instance \"<JsonResponse status_code=200, \"application/json\">\"."
    }
  ],
  "data": {
    "job_seeker": null
  }
}

我什至试过这个

def resolve_job_seeker(self, info, **kwargs):
    if info.context.user.is_authenticated:
        try:
            profile = Profile.objects.get(user=info.context.user)
            try:
                job_seeker = models.JobSeeker.objects.get(profile=profile)
                return job_seeker
            except:
                return models.JobSeeker.objects.none()
        except Profile.DoesNotExist:
            return []
    return None

我仍然遇到这样的问题

{
  "errors": [
    {
      "message": "Received incompatible instance \"<QuerySet []>\"."
    }
  ],
  "data": {
    "job_seeker": null
  }
}
4

1 回答 1

0

如果JobSeeker是模型,那么它应该是JobSeeker.objects.filter。惯例

您不能返回在查询对象中定义的自定义内容。您正在调用get方法。 objects.get()返回单个对象而不是列表。一个更简单的解决方案是调用filter()

job_seeker = JobSeeker.objects.filter(profile=profile)
return job_seeker

如果没有任何匹配的配置文件,它将返回一个空列表。在这两种情况下,只需返回求职者即可。如果这是您想要的,则无需使用像 data 这样的额外字段。

def resolve_job_seeker(self, info, **kwargs):
    if info.context.user.is_authenticated:
        try:
            profile = Profile.objects.get(user=info.context.user)
            job_seeker = JobSeeker.objects.filter(profile=profile)
            return job_seeker
        except Profile.DoesNotExist:
            raise Exception("Profile is not created for this user")
    raise Exception("user not logged in")
于 2019-07-07T18:21:38.470 回答