Django休息总是创建新实例

时间:2015-12-08 00:26:28

标签: python django django-rest-framework mongoengine

我想知道是否有人能回答我为什么会这样。

serializers.py:

class UserStatisticsMongdoDocumentSerializer(DynamicDocumentSerializer):
    class Meta:
        model = UserStatisticsMongdoDocument
        depth = 2
        fields = ('id','owner','last_modified','game_complete','level')

    def save_or_update(self,validated_data):
      username = validated_data['owner']
      print ("save_or_update val_data: " + str(validated_data))
      try:
        instance = UserStatisticsMongdoDocument.objects.get(id=username)
        print ("FOUND")
      except UserStatisticsMongdoDocument.DoesNotExist:
        print ("DoesNotExist => creating new")
        self.save(validated_data=validated_data)
      else:
        print ("Exists => updating")
        self.update(instance=instance,validated_data=validated_data)

models.py:

class UserStatisticsMongdoDocument(DynamicDocument):
  owner = StringField(required=True, unique=True,primary_key=True)
  last_modified = DateTimeField(required=True, default=datetime.datetime.now)
  game_complete = BooleanField(required=True)
  level = IntField(required=True)

  # game_stats = EmbeddedDocumentField(document_type=GameStatistics)
  # level_stats = EmbeddedDocumentField(document_type=LevelStatistics)

  def __str__(self):
    return "UserStatisticsMongdoDocument  { owner:" + self.owne +"}"

views.py:

class UserStatisticsMongoDocumentList(drfme_generics.GenericAPIView):
    authentication_classes = (TokenAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated, IsNotAndroidSuperuser,)
    queryset = UserStatisticsMongdoDocument.objects.all()
    serializer_class = UserStatisticsMongdoDocumentSerializer

    def post(self, request, format=None):
        print ("UserStatisticsMongoDocumentList -> post")
        data = JSONParser().parse(request)
        data['owner'] = request.user.username
        serializer = UserStatisticsMongdoDocumentSerializer(data = data)
        if serializer.is_valid():
            serializer.save_or_update(validated_data=serializer.validated_data)
            return Response("ok")
        return Response("not ok")

请求:

POST /api/mongoPostStatistics/ HTTP/1.1
Host: 127.0.0.1:8000
Authorization: Basic
-------------------------------------------
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 94ccfc5e-4d53-3118-bd96-87f59d6edeab

{
    "game_complete":"false",
    "level":"1"
}

我第一次发布此请求时会得到以下输出:

UserStatisticsMongoDocumentList -> post
save_or_update val_data: OrderedDict([('owner', 'wTHUiRpWy9LBKX2p'), ('last_modified', datetime.datetime(2015, 12, 8, 0, 8, 20, 833558)), ('game_complete', False), ('level', 1)])
DoesNotExist => creating new

我在db中看到一个实例

但是,如果再次发布,我会

UserStatisticsMongoDocumentList -> post
save_or_update val_data: OrderedDict([('owner', 'wTHUiRpWy9LBKX2p'), ('last_modified', datetime.datetime(2015, 12, 8, 0, 8, 20, 833558)), ('game_complete', False), ('level', 1)])
DoesNotExist => creating new

但我应该得到

UserStatisticsMongoDocumentList -> post
save_or_update val_data: OrderedDict([('owner', 'wTHUiRpWy9LBKX2p'), ('last_modified', datetime.datetime(2015, 12, 8, 0, 8, 20, 833558)), ('game_complete', False), ('level', 1)])
Found
Exists => updating

但是我仍然只在DB中输入一个条目,如果我更改了任何字段中的值,它也会在数据库中更新。

这是我的数据库条目:

{
"_id" : "wTHUiRpWy9LBKX2p",
"last_modified" : ISODate("2015-12-08T00:06:24.846Z"),
"game_complete" : false,
"level" : 1,
"validated_data" : {
    "last_modified" : ISODate("2015-12-08T00:06:24.846Z"),
    "owner" : "wTHUiRpWy9LBKX2p",
    "level" : 1,
    "game_complete" : false
}
}

我的问题是:

1 - 为什么我第二次使用相同的'所有者'

发布请求时却找不到它

2 - 如果它确实找不到它(并且它不会导致它抛出一个被捕获的错误),那么执行.save()方法应该创建一个新条目,但它以某种方式更新旧条目 - 为什么?(https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/master/rest_framework_mongoengine/serializers.py

3 - 为什么我的数据库条目中会出现一个名为“validated_data”的字段?

谢谢

1 个答案:

答案 0 :(得分:1)

1 - 为什么我第二次使用相同的'所有者'

发布请求时找不到它

在序列化程序中,它应该是instance = UserStatisticsMongdoDocument.objects.get(id=username)中的pk = username或owner = username而不是id = username,因为所有者字段现在是主键。

  1. 为什么我会得到一个名为" validated_data"在我的数据库条目
  2. 无论你在save()方法中传递什么,它都将是存储在db中的额外数据。 http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save