我正在使用 Django rest 框架在 MongoDB 中保存记录。迁移如下 -
# Generated by Django 3.0.5 on 2021-01-17 10:39
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Demo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('description', models.CharField(default='', max_length=1000)),
('user_id', models.IntegerField()),
('published', models.BooleanField(default=False)),
],
),
]
但是 MongoDB 中的记录没有自动创建的 id
{
"_id" : ObjectId("6004354240e7097e5b392e5c"),
"description" : "sdf asdaaaaaaaaaaaaaaaaaaaaaaaaaaa ass d",
"user_id" : 11,
"published" : false
}
使用插入记录serializer.save()
添加记录的功能如下
def demo_add(request):
user_id=request.user.id
tutorial_data = JSONParser().parse(request)
demo_serializer = DemoSerializer(data=tutorial_data)
if demo_serializer.is_valid():
demo_serializer.save({"user_id":user_id ,"description":tutorial_data['description']})
return JsonResponse({"result": True})
return JsonResponse({"result":False,"msg":"Invalid validation"}, status=status.HTTP_400_BAD_REQUEST)