使用mongodb的Django rest-framework没有创建自动字段主键ID [英] Django rest-framework with mongodb not creating auto field primary key id
问题描述
我正在使用Django rest框架将记录保存在MongoDB中.迁移如下-
I am saving records in MongoDB using Django rest framework. Migration is as below -
# 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
But the records in MongoDB doesn't have auto-created id in it
{
"_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)
推荐答案
Django已经在后台为您解决了这一问题,因此您不必这样做,如您所见:
Django already take care of that for you in the background so you don't have to, as you can see:
auto_created = True,primary_key = True,serialize = False,verbose_name ='ID')
auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
{
"_id" : ObjectId("6004354240e7097e5b392e5c"),
"description" : "sdf asdaaaaaaaaaaaaaaaaaaaaaaaaaaa ass d",
"user_id" : 11,
"published" : false
}
第一行是您的ID,每次创建对象时,ID都会不同.
First line is your ID, each time an object is created, the ID will be different.
尽管没有更多的代码也很难更具体
Although without more code is difficult to be more specific
这篇关于使用mongodb的Django rest-framework没有创建自动字段主键ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!