我已经弄明白了这一点,但我找不到答案,并将张贴,因为有人可能会发现它有帮助。
下面是导致问题的代码:
models.py
class SModelQuerySet(models.QuerySet):
def stubbed_outputs(self):
return self.defer("outputs").annotate(
has_outputs=models.Case(
models.When(
models.Q(~models.Q(outputs={}) & models.Q(outputs__isnull=False)),
then=True,
),
default=False,
output_field=models.BooleanField(),
)
)
def for_user(self, user):
return self.filter(user=user)
class SModelManager(models.Manager):
def get_queryset(self):
return SModelsQuerySet(self.model, using=self._db).stubbed_outputs()
def for_user(self, user):
return self.get_queryset().for_user(user)
class OutputsManager(models.Manager):
def get_queryset(self):
return super().get_queryset().only("outputs")
def for_user(self, user):
return self.get_queryset().filter(user=user)
class SModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True)
name = models.CharField(max_length=50)
description = models.CharField(max_length=500, null=True, blank=True)
inputs = models.JSONField(default=dict)
outputs = models.JSONField(default=dict)
objects = SModelManager()
outputs_objects = OutputsManager()
class Meta:
verbose_name_plural = "scientific models"
db_table = "smodels"
managed = False
def __str__(self):
return self.name
views.py
class SharedModelViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.SharedModelSerializer
@action(detail=True, methods=["post"])
def save(self, request, pk=None):
shared_model = self.get_object()
model = get_object_or_404(
models.SModel.objects.filter(user=shared_model.share_from),
pk=shared_model.model_to_share_id,
)
model.pk = None
model.user_id = shared_model.share_to.id
model.save()
shared_model.delete()
return Response(
serializers.SModelSerializer(model).data, status=status.HTTP_200_OK
)
当这个视图试图保存时,我得到了这样的错误:"ValueError: Cannot force an update in save() with no primary key."
我无法弄清楚这一点,它是工作几个星期前。
1条答案
按热度按时间bqucvtff1#
问题:返回模型的查询--只是检查共享模型是否确实由具有共享权限的用户共享--具有延迟字段。这些字段被延迟,因为它们是需要很长时间查询的大规模JSON对象。
解决方案:添加一个单独的管理器模型。管理器返回查询的所有字段。然后模型保存得很好。