你好,我遇到了一个我自己无法解决的问题。我尝试在create内调用函数create_with_celery,但没有成功
我应该如何使用适当的参数来调用create.delay?我不知道如何正确调用create函数来使工作人员创建对象
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
@app.task(bind=True)
def create(self, request):
article = Article.objects.create(link=request.data['link'])
article.save()
serializer = ArticleSerializer(article, many=False)
words = WordList(article.link)
# take every 90nth word for faster loading only dev approach
i = 0
for word in range(0, len(words.list)):
# try to take word from database
i += 1
try:
existing_word = Word.objects.filter(name=words[word])
Word.objects.create(
name=existing_word[0].name,
advance_level=existing_word[0].advance_level,
definition=existing_word[0].definition,
article=Article.objects.get(id=article.id)
)
print('word nr {}/{} "{}" created from database'.format(i,
len(words.list), words[word]))
except:
# if it's not existing fetch data from web
Word.objects.create(
name=words[word],
advance_level=get_word_frequency(words[word]),
definition=get_word_definition(words[word]),
article=Article.objects.get(id=article.id)
)
print('word nr {}/{} "{}" fetched from web'.format(i,
len(words.list), words[word]))
response = {'message': 'Article created ', 'result': serializer.data}
return Response(response, status=status.HTTP_200_OK)
我正在尝试执行类似的操作,但出现错误“类型为'Article'的对象不是JSON可序列化的“]
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
@app.task(bind=True)
def create_with_celery(self, article, serializer, words, req):
i = 0
for word in range(0, len(words.list)):
# try to take word from database
i += 1
try:
existing_word = Word.objects.filter(name=words[word])
Word.objects.create(
name=existing_word[0].name,
advance_level=existing_word[0].advance_level,
definition=existing_word[0].definition,
article=Article.objects.get(id=article.id)
)
print('word nr {}/{} "{}" created from database'.format(i,
len(words.list), words[word]))
except:
# if it's not existing fetch data from web
Word.objects.create(
name=words[word],
advance_level=get_word_frequency(words[word]),
definition=get_word_definition(words[word]),
article=Article.objects.get(id=article.id)
)
print('word nr {}/{} "{}" fetched from web'.format(i,len(words.list), words[word]))
def create(self, request):
article = Article.objects.create(link=request.data['link'])
article.save()
serializer = ArticleSerializer(article, many=False)
words = WordList(article.link)
req = request
self.create_with_celery.delay(article, serializer, words, req)
response = {'message': 'Article created ', 'result': serializer.data}
return Response(response, status=status.HTTP_200_OK)
您只能传递JSON支持的基本类型。
[请记住,芹菜是处理异步数据的好工具,正如我所见,您尝试在ArticleViewSet
上执行的操作,您可以直接在ArticleSerializer
的save方法上实现。