Django 休息总是创建新实例
Django rest always creating new instance
我想知道是否有人可以回答我为什么会这样。
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"
}
我第一次 post 这个请求时得到以下输出:
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
并且我在我的数据库中看到了一个实例
但是,如果 post 它再次出现,我会得到
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
但是我在数据库中仍然只有一个条目,如果我更改了任何字段中的值,它也会在数据库中更新。
这是我的数据库条目:
{
"_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 - 为什么我第二次 post 使用相同 'owner'
的请求时找不到它
2 - 如果它真的没有找到它(并且它不会导致它抛出一个被捕获的错误)然后执行 .save() 方法应该创建一个新条目,但它以某种方式更新旧的一 - 为什么?( https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/master/rest_framework_mongoengine/serializers.py )
3 - 为什么我的数据库条目中有一个名为 "validated_data" 的字段?
谢谢
1 - 为什么它第二次找不到它 post 具有相同 'owner'
的请求
在序列化程序中,它应该是 pk=username 或 owner=username 而不是 instance = UserStatisticsMongdoDocument.objects.get(id=username)
中的 id=username,因为 owner 字段现在是主键。
- 为什么我的数据库条目中有一个名为 "validated_data" 的字段
无论您在 save() 方法中传递什么,它都是存储在数据库中的额外数据。 http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save
我想知道是否有人可以回答我为什么会这样。
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"
}
我第一次 post 这个请求时得到以下输出:
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
并且我在我的数据库中看到了一个实例
但是,如果 post 它再次出现,我会得到
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
但是我在数据库中仍然只有一个条目,如果我更改了任何字段中的值,它也会在数据库中更新。
这是我的数据库条目:
{
"_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 - 为什么我第二次 post 使用相同 'owner'
的请求时找不到它2 - 如果它真的没有找到它(并且它不会导致它抛出一个被捕获的错误)然后执行 .save() 方法应该创建一个新条目,但它以某种方式更新旧的一 - 为什么?( https://github.com/umutbozkurt/django-rest-framework-mongoengine/blob/master/rest_framework_mongoengine/serializers.py )
3 - 为什么我的数据库条目中有一个名为 "validated_data" 的字段?
谢谢
1 - 为什么它第二次找不到它 post 具有相同 'owner'
的请求在序列化程序中,它应该是 pk=username 或 owner=username 而不是 instance = UserStatisticsMongdoDocument.objects.get(id=username)
中的 id=username,因为 owner 字段现在是主键。
- 为什么我的数据库条目中有一个名为 "validated_data" 的字段
无论您在 save() 方法中传递什么,它都是存储在数据库中的额外数据。 http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save