GraphQL新手。因此,我试图使用graphene在Django中编写一个架构,该架构将使用country参数作为String并将time参数作为Character。该查询可以使用“时间”参数正常运行,但是每当我添加“国家”参数时。它会引发以下错误"Unknown argument \"country\" on field \"allNews\" of type \"Query\".",
。这是我的架构和类型:
类型:
class NewsType(DjangoObjectType):
class Meta:
model = News
fields = ('id', 'site_name', 'title', 'link', 'content', 'thumbnail', 'status', 'upvote', 'downvote', 'published_date',
'paper', 'created_date')
filter_fields = ['site_name', 'status', 'country']
interfaces = (CustomNewsNode, )
vote_status = DjangoFilterConnectionField(UserVoteNewsType)
def resolve_vote_status(self, info, user_id):
return self.uservotenews_set.filter(user_id=user_id)
架构:
class NewsTypeFilter(django_filters.FilterSet):
class Meta:
model = News
fields = ['id', 'site_name', 'title', 'link', 'content', 'thumbnail', 'status', 'upvote', 'downvote', 'published_date',
'paper', 'created_date']
class Query(graphene.ObjectType):
all_news = DjangoFilterConnectionField(
NewsType, filterset_class=NewsTypeFilter, time=graphene.String())
def resolve_all_news(self, info, **kwargs):
print(kwargs['country'])
env = environ.Env()
environ.Env.read_env()
HOURS_AFTER_NEWS_VISIBLE = env('HOURS_AFTER_NEWS_VISIBLE')
timeDiff = datetime.now() - timedelta(hours=int(HOURS_AFTER_NEWS_VISIBLE))
if kwargs['time']: # if user clicks on sort by button
if(kwargs['time'] == 'd'):
time = 1
elif (kwargs['time'] == 'w'):
time = 7
elif (kwargs['time'] == 'm'):
time = 30
elif (kwargs['time'] == 'y'):
time = 365
else:
time = 1000
end_of_give_time_period = datetime.now(
) - timedelta(days=int(HOURS_AFTER_NEWS_VISIBLE))
start_of_given_time_period = end_of_give_time_period - \
timedelta(days=time)
allNews = News.objects.order_by('created_date').filter(status=True,
created_date__lte=end_of_give_time_period, created_date__gte=start_of_given_time_period).order_by('-upvote')
else:
allNews = News.objects.order_by(
'-created_date').filter(status=True).filter(created_date__lte=timeDiff)
if 'country' in kwargs:
countryId = Country.objects.filter(
name=kwargs['country'][0]).values_list('pk', flat=True)
allNews = allNews.filter(country__in=[countryId[0]])
return allNews
但是无论何时输入查询,它都会返回以下错误:
查询:
query{
allNews (time :"w", country: "Bangladesh") {
edges{
node{
title
upvote
createdDate
}
}
}
}
输出:
{
"errors": [
{
"message": "Unknown argument \"country\" on field \"allNews\" of type \"Query\".",
"locations": [
{
"line": 2,
"column": 23
}
]
}
]
}
答案 0 :(得分:0)
首先,我从架构中剥离了NewsTypeFilter
,因为它返回的与我的NewsType
相同。然后,我在country
上添加了NewsType
和其他字段。那几乎解决了问题。
我想首先添加filterType会造成问题。