我现在已经解决了这个问题,请向下滚动到问题的底部以查看解决方案
在Django Rest Framework中,当插入发生在一个模型上时,我想在其他模型上进行更新/插入。
我正在使用ModelViewSet
,我尝试覆盖perform_create
方法,但原始插入只是被吞下,没有更新,也没有看到任何错误。
我试过这个
def perform_create(self, serializer):
serializer.save()
但是虽然没有抛出任何错误,但也没有更新。
非常感谢覆盖perform_create
的示例,以便原始插入仍然存在,但是可以同时进行其他更新/插入。
我正在使用DRF 3.5.3。
编辑:这是完整的ModelViewSet代码。
class AttemptViewSet(viewsets.ModelViewSet):
'''
API endpoint that allows Attempt to be CRUDed.
'''
queryset = Attempt.objects.all()
serializer_class = AttemptSerializer
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
import pdb;pdb.set_trace()
serializer.save()
def initial(self, request, *args, **kwargs):
'''
Temporary diagnostic code which should
be removed once it's possible to update
an Attempt
'''
import os
import json
# 'request_auth': request.auth,
log_data = {
'user': request.user.pk,
'remote_address': request.META['REMOTE_ADDR'],
'request_method': request.method,
'request_path': request.get_full_path(),
'request_body': request.data ,
'request_query_params': request.query_params
}
if not os.path.exists('/tmp/spellsplashlog'):
os.makedirs('/tmp/spellsplashlog')
with open('/tmp/spellsplashlog/logging.json', 'w') as f:
json.dump(log_data, f, sort_keys=True, indent=4)
viewsets.ModelViewSet.initial(self, request, *args, **kwargs)
......这是序列化器......
class AttemptSerializer(serializers.ModelSerializer):
class Meta:
model = Attempt
fields = '__all__'
......这是模特......
class Attempt(models.Model):
learner = models.ForeignKey(Learner, related_name='learnerattempts')
word = models.ForeignKey(Word, related_name='wordattempts')
when = models.DateTimeField(auto_now_add=True)
success = models.BooleanField(default=False)
class Meta:
ordering = ['-when']
class JSONAPIMeta:
resource_name = "attempts"
def __str__(self):
formatted_when = localtime(self.when).strftime('%d-%b-%Y %X')
if self.success:
formatted_success = "YES"
else:
formatted_success = "NO"
return u'%s - %s- Success ?: %s ' % (self.word, formatted_when, formatted_success)
编辑(及决议)
好的,所以我对perform_create
进行了一些更改,似乎有些非常微妙的方式DRF不喜欢嵌入pdb.set_trace
。它并没有失败,但它只是没有回应。一旦我删除它,它就像我期望的那样工作。
FWIW在调查过程中我也改变了
serializer.save
到
super().perform_create(serializer)
但事实上,在pdb.set_trace
被移除后,这两者中的任何一个都有效。
答案 0 :(得分:0)
你可以在serializer.save方法接到调用后更新另一个模型。
def perform_create(serializer):
serializer.save()
### here you can write the other logic of update
### you can use the signal, just raise signal on save of that model